原題:
A Ducci sequence is a sequence of n-tuples of integers. Given an n-tuple of integers (a 1 ,a 2 ,···,a n ), the
next n-tuple in the sequence is formed by taking the absolute differences of neighboring integers:
(a 1 ,a 2 ,···,a n ) → (|a 1 − a 2 |,|a 2 − a 3 |,···,|a n − a 1 |)
Ducci sequences either reach a tuple of zeros or fall into a periodic loop. For example, the 4-tuple
sequence 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 tuple
or a periodic loop.
Input
Your program is to read the input from standard input. The input consists of T test cases. The number
of test cases T is given in the first line of the input. Each test case starts with a line containing an
integer n (3 ≤ n ≤ 15), which represents the size of a tuple in the Ducci sequences. In the following
line, n integers are given which represents the n-tuple of integers. The range of integers are from 0 to
1,000. You may assume that the maximum number of steps of a Ducci sequence reaching zeros tuple
or making a loop does not exceed 1,000.
Output
Your program is to write to standard output. Print exactly one line for each test case. Print ‘LOOP’ if
the Ducci sequence falls into a periodic loop, print ‘ZERO’ if the Ducci sequence reaches to a zeros tuple.
Sample Input
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
Sample Output
ZERO
LOOP
ZERO
LOOP
中文:
紫書上的練習題,給你n個數,這n個數可以分別和下一個數相減,如下(a 1 ,a 2 ,···,a n ) → (|a 1 − a 2 |,|a 2 − a 3 |,···,|a n − a 1 |)。如果,不斷進行這樣的操作,如果出現全是0輸出ZERO,如果出現迴圈輸出LOOP。資料保證出現迴圈或者0
#include <bits/stdc++.h>using namespace std;set<vector<int>> sv;int main(){ ios::sync_with_stdio(false); int t,n; cin>>t; while(t--) { cin>>n; vector<int> v,emp(n,0); sv.clear(); for(int i=0;i<n;i++) { int x; cin>>x; v.push_back(x); } sv.insert(v); int flag=0; vector<int> tmp; while(true) { tmp.clear(); for(int i=0;i<n-1;i++) tmp.push_back(abs(v[i+1]-v[i])); tmp.push_back(abs(v[n-1]-v[0])); v=tmp; if(sv.find(emp)!=sv.end()) { flag=1; break; } if(sv.find(tmp)!=sv.end()) { flag=2; break; } sv.insert(tmp); } if(flag==1) cout<<"ZERO"<<endl; else cout<<"LOOP"<<endl; } return 0;}
解答:
紫書上的練習題,題目很簡單,利用vector重載好的一系列操作儲存多個值,然後利用set判斷是否有重複即可。