A Ducci sequence is a sequence of n-tuples of integers. Given an n-tuple of integers (a1, a2, · · · , an),the next n-tuple in the sequence is formed by taking the absolute differences of neighboring integers:(a1, a2, · · · , an) → (|a1 − a2|, |a2 − a3|, · · · , |an − a1|)Ducci sequences either reach a tuple of zeros or fall into a periodic loop. For example, the 4-tuplesequence starting with 8,11,2,7 takes 5 steps to reach the zeros tuple:(8, 11, 2, 7) → (3, 9, 5, 1) → (6, 4, 4, 2) → (2, 0, 2, 4) → (2, 2, 2, 2) → (0, 0, 0, 0).The 5-tuple sequence starting with 4,2,0,2,0 enters a loop after 2 steps:(4, 2, 0, 2, 0) → (2, 2, 2, 2, 4) → (0,0,0,2,2) → (0, 0, 2, 0, 2) → (0, 2, 2, 2, 2) → (2, 0, 0, 0, 2) →(2, 0, 0, 2, 0) → (2, 0, 2, 2, 2) → (2, 2, 0, 0, 0) → (0, 2, 0, 0, 2) → (2, 2, 0, 2, 2) → (0, 2, 2, 0, 0) →(2, 0, 2, 0, 0) → (2, 2, 2, 0, 2) → (0, 0, 2, 2, 0) → (0, 2, 0, 2, 0) → (2, 2, 2, 2, 0) → (0,0,0,2,2) → · · ·Given an n-tuple of integers, write a program to decide if the sequence is reaching to a zeros tupleor a periodic loop.InputYour program is to read the input from standard input. The input consists of T test cases. The numberof test cases T is given in the first line of the input. Each test case starts with a line containing aninteger n (3 ≤ n ≤ 15), which represents the size of a tuple in the Ducci sequences. In the followingline, n integers are given which represents the n-tuple of integers. The range of integers are from 0 to1,000. You may assume that the maximum number of steps of a Ducci sequence reaching zeros tupleor making a loop does not exceed 1,000.OutputYour program is to write to standard output. Print exactly one line for each test case. Print ‘LOOP’ ifthe Ducci sequence falls into a periodic loop, print ‘ZERO’ if the Ducci sequence reaches to a zeros tuple.Sample Input448 11 2 754 2 0 2 070 0 0 0 0 0 061 2 3 1 2 3Sample OutputZEROLOOPZEROLOOP
分析:
一开始用数组做,然后,每生成一个新的数组就存入,然后判断,结果就是超时……
后来用了map和vector(不用每个都存,每次都重新遍历判断了!)
思路:
用map<vector<int>,int>b;来存每一组数,第一次存入时b[a]=1;
如果值大于1就出现了loop的情况!
代码如下:
#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
#include<cmath>
using namespace std;
vector<int> a;
map<vector<int>,int> b;
bool judgeZero(vector<int> x,int n){
for(int i=0;i<n;i++){
if(x[i]!=0)return false;
}
return true;
}
int main(){
int n,m,p;
cin>>n;
while(n--){
int k;
b.clear();//每次都要清空!
a.clear();
cin>>m;
for(int i=0;i<m;i++){
cin>>p;
a.push_back(p);
}
if(judgeZero(a,m)){cout<<"ZERO"<<endl;continue;}
b.insert(pair<vector<int>,int>(a,1));
vector<int> a1,c;
c=a;
for(int i=0;i<=1000;i++){
a1.clear();//记得要清空啊,不然用push_back每次都忘后面加了(会超过m)
for(int j=0;j<m-1;j++){
int y=abs(c[j]-c[j+1]);
a1.push_back(y);
}
a1.push_back(abs(c[m-1]-c[0]));
c=a1;
if(judgeZero(a1,m)){
cout<<"ZERO"<<endl;
break;
}
if(!b.count(a1)){
b.insert(pair<vector<int>,int>(a1,1));
}
else{
cout<<"LOOP"<<endl;
break;
}
}
}
}