$CF1141C Polycarp Restores Permutation$

\(problem\)

这题的大致意思就是已知数值差值 求1-n的排列
~~~
如果能构成排列 则输出这个排列。如果不能则输出-1
~~~
~~~
排列的值都是 大于1 而小于n的 而且没有相同的数字。
~~~
~~~
这题最关键的是 怎么输出这个序列 有的是存在负数的。

那么 考虑一下排列都是从1到n的对不对。
取序列的最小值 然后用\(1 - Min\)即是整个序列应该加上的数值。
首先考虑判重。 用数组 或者用\(map or set\)
都是不错的方法。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
inline LL In() { LL res(0),f(1); register char c ;
    while(isspace(c=getchar())) ; c == '-'? f = -1 , c = getchar() : f = 1 ;
    while(res = (res << 1) + (res << 3) + (c & 15) , isdigit(c=getchar())) ; return res * f ;
}
int n ;
int p[200000+5] ;
int res[200000+5] ;
set<int> s;//判重
signed main(){
    n = In() ;
    for(register int i=1;i<=n-1;i++) p[i] = In() ;
    res[1] = 0 ;
    for(register int i=2;i<=n;i++) res[i] = res[i-1] + p[i-1] ;//计算前缀和
    int Min = 0x7f7f7f7f;
    for(register int i=1;i<=n;i++){
        Min = min(res[i],Min);
        if(s.count(res[i])==0) s.insert(res[i]) ;//插入数值
        else {
            cout << -1 << endl ;//如果存在重复的数值则不可能构成排列。
            return 0 ;
        }
    }
    //cout << Min << endl ;
    int c = 1 - Min ;
    bool f = false;
    for(register int i=1;i<=n;i++) {
        if(res[i] + c > n) {//如果大于n则不能构成 也是输出-1
            cout << -1 << endl ;
            return 0 ;
        }
    }
    
    for(register int i=1;i<=n;i++) {
        cout << res[i] + c << ' ' ;
    }
    return 0 ;
}

猜你喜欢

转载自www.cnblogs.com/qf-breeze/p/10564198.html
今日推荐