1. 程式人生 > >C. Polycarp Restores Permutation

C. Polycarp Restores Permutation

最小值 res pre pan min == div tor perm

鏈接: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;
}

  

C. Polycarp Restores Permutation