错题笔记1.6-07:有趣的跳跃

错题收集,自己做怎么样都不能AC,是因为我写的长这样:

#include<iostream>
#include<cmath>
using namespace std;
int main(){
    int n,m,o=-2;
    cin>>n;
    int z[n],y[n-1];
    cin>>z[0];
    if(n==1){
        cout<<"Jolly";
    } else {
    for(int i=1;i<n;i++){
        cin>>z[i];
        y[i-1]=abs(z[i]-z[i-1]);
    }
    for(int i=0;i<n-2;i++){
        if(abs(y[i+1]-y[i])!=1){ //这里判断不是很正确?假如是一个这样的摆动数列:n-2 n-1 n-2 n-1也是能过jolly判断条件...
            cout<<"Not jolly";
            return 0;
        }
    }
    if(y[n-2]==n-1||y[0]==n-1) { cout<<"Jolly"; } else { cout<<"Not jolly"; }
    }
} 

下面是答案:(网上找的)

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
    int n, last, current, a[3001]={0}; //数组每个元素全部初始化为0要记住...
    cin >> n;
    cin >> last;
    for (int i=1; i<n; i++){
        cin >> current;
        a[int(abs(current-last))]++; //巧妙利用从1到n-1这个特点,注意以后要记住数组的特点...
                //abs这里我在Linux下编译出错?是我编译器太新还是啥?说abs输出的type是double,所以加int变量强制转换编译通过
        last = current;
    } 
    for (int i=1; i<n; i++){
        if (a[i] != 1){
            cout << "Not jolly" << endl;
            return 0;
        }
    }
    cout << "Jolly" << endl;
    return 0;
}

标签: none

添加新评论