习题5_2 Ducci序列(Ducci Sequence, ACM/ICPC Seoul 2009, UVa1594)
题目描述:
对于一个元组(a1,a2…,an),可以堆每个数求出它和下一个数的差的绝对值,得到一个新的n元组(|a1-a2|, |a2-a3|, …, |an-a1|)。重复这个过程,得到的序列称为Ducci序列,例如(8, 11, 2, 7) -> (3, 9, 5, 1) -> (6, 4, 4, 2) -> (2, 0, 2, 4) -> (2, 2, 2) -> (0, 0, 0, 0).
也有的Ducci序列最终会循环。输入n元组(3 <= n <= 15),你的任务是判断它最终会变成0还是会循环。输入保证最多1000步就会变成0或者循环。
#include<cstdio>
#include<iostream>
#include<vector>
#include<set>
#include<cmath>
using namespace std;
const int MAX_N = 1010;
vector<int> seq[2];
set<vector<int> > s;
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int k;
cin >> k;
while(k--) {
int n, x;
cin >> n;
seq[0].clear();
s.clear();
while(n--) {
cin >> x;
seq[0].push_back(x);
}
for(int i = 0; i < 1010; i++) {
seq[1].clear();
s.insert(seq[0]);
int cnt_zero = 0;
for(int j = 0; j < seq[0].size(); j++) {
seq[1].push_back(j==seq[0].size() - 1 ? abs(seq[0][j]-seq[0][0]) : abs(seq[0][j] - seq[0][j+1]) );
if(seq[1][j] == 0) cnt_zero++;
//cout << seq[1][j] << " ";
}
if(s.count(seq[1])) { cout << "LOOP\n"; break; }
if(cnt_zero == seq[1].size()) { cout << "ZERO\n"; break; }
seq[0].clear();
for(int j = 0; j < seq[1].size(); j++) seq[0].push_back(seq[1][j]);
}
}
return 0;
}