ACM编程:习题5-2 Ducci序列(Ducci Sequence, ACM/ICPC Seoul 2009, UVa1594)

刘汝佳的书上提示说用vector,然而我很任性地用queue做了,也算是提供一种不同的做法吧。有很多空行的情况下,一共也就不到50行,相比其他人又是vector又是map的,我觉得还是我的代码最美最可爱,哼(ˇˍˇ) 

 

 

/*

找了下英文原版题目是这样:

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.

*/

因为做的时候书上没给输入输出案例,我就大概按解决问题的思路把代码写出来了,输入输出的控制可能不标准。

 

 

#include
#include
#include

using namespace std;

int main(){
    int n, temp, a, b, c, tail, kase;
    queue num;
    cin >> n;
    for(int i = 0; i < n; i++){
       cin >> temp;
       num.push(temp);
    }

    kase = 0;
    bool zero = false;
    while(!zero && kase < 1001){
        zero = true;
        tail = a = num.front();
        num.pop();
        for(int i = 0; i < n-1; i++){
            b = num.front();
            num.pop();
            c = abs(a - b);
            if(c != 0) zero = false;
            num.push(c);
            a = b;
        }

        b = tail;
        c = abs(a - b);
        if(c != 0) zero = false;
        num.push(c);

        if(zero) break;
        kase++;
    }

    if(zero && kase < 1001)
        cout << "SUCCESS" << endl;
    else
        cout << "FAIL" << endl;

    return 0;
}

 

 

 

 

 

你可能感兴趣的:(ACM)