2014-08-28 解題區/解題區 - UVa UVa 1594 - Ducci Sequence contents 1. Problem2. Sample Input3. Sample Output4. Solution Problem將序列根據步驟轉換,是否會產生迴圈或者是回歸到 0。 Sample Input1234567894 4 8 11 2 7 5 4 2 0 2 0 7 0 0 0 0 0 0 0 6 1 2 3 1 2 3 Sample Output1234ZERO LOOP ZERO LOOP Solution用 hash (RS hashing) 來壓縮一下儲存的方式,碰撞的機率應該是挺低的。 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#include <stdio.h>#include <stdlib.h>#include <math.h>#include <vector>#include <assert.h>#include <map>#include <algorithm>using namespace std;int nextSeq(int A[], int n) { int B[32]; A[n] = A[0]; for (int i = 0; i < n; i++) B[i] = abs(A[i] - A[i+1]); for (int i = 0; i < n; i++) A[i] = B[i]; return 1;}int main() { int testcase, n, A[32]; scanf("%d", &testcase); while (testcase--) { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &A[i]); map<int, int> R; do { int ok = 1, hash = 0; int a = 63689, b = 378551; for (int i = 0; i < n; i++) { hash = hash * a + A[i], a = a * b; ok &= A[i] == 0; } if (ok) { puts("ZERO"); break; } int &f = R[hash]; if (f) { puts("LOOP"); break; } f = 1; } while (nextSeq(A, n)); } return 0;}/* 4 4 8 11 2 7 5 4 2 0 2 0 7 0 0 0 0 0 0 0 6 1 2 3 1 2 3 */ Newer UVa 1635 - Irrelevant Elements Older UVa 1590 - IP Networks