[刷题]算法竞赛入门经典/第五章/Ducci序列(习题5-2)

Ducci Sequence (UVA原题的链接单击这里哦???)


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
-------------------------------------------------
/* UVA1594 UVALive4723 Ducci Sequence */
//包含了目前c++所包含的所有头文件
#include 
using namespace std;

vector item, zero;
set< vector> items;//用于保存每个过程的元组

//传容器的引用
bool judge(vector &item, set< vector> &items, vector &zero, int n) {
    int step = 0;//用于保存循环次数
    for (;;) {
        if (item == zero) return true;//如果一个元组全部元素为零
        int a0 = abs(item[0] - item[1]);//将第一个位置上将要改变的元素临时保存
        for (int i = 1; i < n; i++)//将第二个位置到最后一个位置进行操作
            item[i] = abs(item[i] - item[(i + 1) % n]);
        item[0] = a0;
        // 因为set容器中的所有元素都是唯一的,所以函数只能返回1(如果找到元素)或零,
        // 用set的count函数来判断是不是进入循环了
        if (items.count(item) || step++ > 1000) return false;
        else items.insert(item);
    }
}
int main()
{
    int t, n;
    cin >> t;
    while (t--) {       //要测试的元组数量
        item.clear();
        zero.clear();
        items.clear();

        int a;          //a:每个元组中的元素  flag:每个测试元组的循环步数
        cin >> n;             //每个测试元组的元素数目
        for (int i = 0; i < n; i++) {
            cin >> a;
            item.push_back(a);//初始化
            zero.push_back(0);
        }
        //判断
        if (judge(item, items, zero, n)) puts("ZERO");
        else puts("LOOP");
    }
    return 0;
}



 

你可能感兴趣的:(LeetCode)