C. Polycarp Restores Permutation

时间:2019-03-21
本文章向大家介绍C. Polycarp Restores Permutation,主要包括C. Polycarp Restores Permutation使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

链接:https://codeforces.com/contest/1141/problem/C

题意:

给n-1个数,

qi=pi+1pi

p为1-n的排列序列

q为给的序列。

根据q求出p, 求不出时为-1。

思路:

另p数组首个为0.求出p数组,再得到p数组中最小的值,将p中所有数减掉最小值再加1得到原p。

同时记录原p中每个数出现的次数。超过一次,说明不能还原 。

代码:

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

const int MAXN = 2e5 + 10;

LL a[MAXN];
map<LL, int> b;

int main()
{
    int n, v;
    cin >> n;
    a[0] = 0;
    LL sum = 0, mmin = 0;
    for (int i = 2;i <= n;i++)
    {
        cin >> v;
        a[i] = a[i - 1] + v;
        sum += a[i];
        mmin = min(mmin, a[i]);
    }
    for (int i = 1;i <= n;i++)
    {
        a[i] = a[i] - mmin + 1;
        if (b[a[i]] == 1 || a[i] > n)
        {
            cout << -1 << endl;
            return 0;
        }
        b[a[i]] = 1;
    }
    for (int i = 1;i <= n;i++)
        cout << a[i] << ' ' ;
    cout << endl;


    return 0;
}