6.Ducci序列(UVA1594)

Ducci序列(UVA1594)

题目简单分析

题目的详细内容可以在这个网站上看到,下面简单说明一下题目要求。
[题意]
对于一个数组(a1, a2, …, an),可以求得一个新的数组(|a1-a2|, |a2-a3|, …, |an-a1|),重复这个过程,直到这个数组全为0或者进入循环。例如:
(8, 11, 2, 7)->(3, 9, 5, 1)->(6, 4, 4, 1)->(2, 0, 2, 4)->(2, 2, 2, 2)->(0, 0, 0, 0)
我们需要做的就是判断给出的数组经过若干次操作之后是全为0还是进入循环。
[输入输出]
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

[分析]
本题只需要进行简单的模拟过程即可。

代码

完整代码如下,C++版本为C++11,VScode的工程在github。代码如有bug,敬请指出。

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cstring>
using namespace std;

const int maxDim=18;
int vec[maxDim];
int nDim=0;

void next(void);
int isZero(void);
int main(){
    string oneLine;
    getline(cin, oneLine);//读掉不用
    while(getline(cin, oneLine)){
        getline(cin, oneLine);//数据行
        stringstream ss(oneLine);//字符串流
        nDim=0;
        while(ss >> (vec[nDim++]));//存入数组
        nDim-=1;
        int cnt = 1100;//最多1000次循环
        while(cnt--){
            next();
            if(isZero()){
                cout << "ZERO" << endl;
                break;
            }          
        }
        if(cnt<=0) cout << "LOOP" <<endl;
    }
    return 0;
}
void next(void){//计算下一个状态
    int temp=vec[nDim-1];
    for(int i=nDim-1;i>0;--i){
        vec[i]=abs(vec[i]-vec[i-1]);
    }
    vec[0]=abs(vec[0]-temp);
}
int isZero(void){//判断是否全为0
    int isZero=1;
    for(int i=0;i<nDim;++i){//全为0
        if(vec[i]!=0) isZero=0;
    }
    if(isZero) return 1;
    else return 0;
}
    

猜你喜欢

转载自blog.csdn.net/weixin_43374723/article/details/84185443
今日推荐