紫书第五章习题 5-2 UVA1594 Ducci Sequence 【模拟】

出处:https://blog.csdn.net/qq_34896694/article/details/54462064
题目链接:https://vjudge.net/contest/231030#problem/B

题意:

对于一个n元组(a1, a2, ... , an),可以对于每个数求出它和下一个数的差的绝对值,得到一个新的 n 元组 (|a1-a2|, |a2-a3|, ... , |an-a1|)。重复这个过程,得到的序列称之为 Ducci 序列。求Ducci数列如果在1000步以内循环了,就输出 LOOP,否则输出 ZERO

题解:

按照题意的方式求出 每个 n 元组,如果步数 >= 1000而还是没有出现全0,则应输出 LOOP(因为题目保证如果出现全0的话是在1000步以内。),否则输出ZERO,注意到 n <= 15,这样的数据运行起来绰绰有余。

附代码:

#include <cstdio>  
#include <cstring>  
#include <iostream>  
#include <algorithm>  
  
using namespace std;  
  
const int size = 25;  
int n;  
int a[size], b[size];  
  
#define rep(i, n ) for (int i = 0; i < n; i++)  
// inline int ABS(int a) { return a < 0 ? a: -a; }  
  
int main() {  
    int test;  
    scanf("%d", &test);  
    while( test -- ) {  
        scanf("%d", &n);  
        rep( i, n ) {  
            scanf("%d", &a[i]);  
        }  
  
        int fg = 1;  
        for ( int cnt = 0; ; cnt ++) {  
            if( cnt >= 1000)  { fg = 0; break; }  
            for ( int i = 1; i < n; i++ ) {  
                b[i-1] = abs(a[i]-a[i-1]);  
            }  
            b[n-1] = abs(a[n-1]-a[0]);  
  
            bool zero = 1;  
            for ( int i = 0; i < n; i++ ) {  
                if(b[i] != 0) zero = 0;   
                a[i] = b[i];  
            }  
            if(zero) break;  
        }  
        if( fg ) puts("ZERO");  
        else puts("LOOP");  
    }  
  
    return 0;  
}  


猜你喜欢

转载自blog.csdn.net/JXUFE_ACMer/article/details/80453982