Polycarp Restores Permutation CodeForces - 1141C
An array of integers p1,p2,…,pn is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4].
Polycarp invented a really cool permutation p1,p2,…,pn of length n. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1 of length n−1, where qi=pi+1−pi.
Given n and q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.
Input
The first line contains the integer n (2≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1 integers q1,q2,…,qn−1 (−n<qi<n).
Output
Print the integer -1 if there is no such permutation of length n which corresponds to the given array q. Otherwise, if it exists, print p1,p2,…,pn. Print any such permutation if there are many of them.
Examples
Input
3
-2 1
Output
3 1 2
Input
5
1 1 1 1
Output
1 2 3 4 5
Input
4
-1 2 2
Output
-1
当时错因:数组没开ll。
极限情况下,n和q[i]都接近上限时,得到的数组值会超int
解法一:假设a[1] == 1, 依次得到后续元素
判断,若有重复元素或数组最大值不等于n, 不成立
#include <iostream>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#define N 2000010
#define ll long long
#define INF 0x4f4f4f4f
using namespace std;
ll ar[N], ta[N];
int main()
{
/*
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
*/
int n, a;
ll tmin = 1, tmax = 0;
scanf("%d", &n);
ar[1] = 1;
for(int i = 1;i < n;i++){
scanf("%d", &a);
ar[i+1] = ar[i] + a;
tmin = min(tmin, ar[i+1]);
}
tmin = -tmin + 1;
for(int i = 1;i <= n;i++)
{
ar[i] += tmin;
ta[i] = ar[i];
tmax = max(tmax, ar[i]);
}
sort(ta + 1, ta + 1 + n);
int sz = unique(ta + 1, ta + 1 + n) - (ta + 1);
//printf("sz is %d tmax is %d\n", sz, tmax);
if(sz != n || tmax != n)
printf("-1");
//printf("\n");
else
for(int i = 1;i <= n;i++) printf("%lld ", ar[i]);
return 0;
}
第二种解法:
sort后,比较相邻两项, 差值不等于1, 即不成立
这个方法不需要开ll也可以过,因为不会超。
sort(ta + 1, ta + 1 + n);
int flag = 1;
for(int i = 1;i < n;i++)
{
if(ta[i+1] - ta[i] != 1){
flag = 0;
break;
}
}
if(flag == 0)
printf("-1");
本文介绍了一种解决Polycarp恢复遗忘排列的问题的算法,通过给定的差值数组q,帮助恢复原始的整数排列p。文章详细阐述了解题思路,包括使用long long类型避免溢出,以及两种解题方法:一是通过假设初始值并检查重复性和最大值,二是通过排序后检查相邻元素差值是否为1来验证排列的有效性。
383

被折叠的 条评论
为什么被折叠?



