暑假热身G题

本文介绍了一种算法,用于根据相邻元素差值序列重建一个特定的排列,确保该排列包含从1到n的所有整数且每个数字仅出现一次。通过实例演示了如何实现这一过程,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://codeforces.com/problemset/problem/1141/C
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
给出数字数量和相邻两项的差问是否能构成一个包含1到n所有数字的数组
假设第一个数字是0,求出当前数组所有数字记录最小值,然后将所有数字减去最小值加1即可;
然后遍历一次看是否满足条件。
注意求最小值时数字可能会很大(流下了不谨慎的泪水),这个时候一定不能满足条件直接退出循环。

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int n,d[200005],a[200005],vis[200005];
int main()
{
	scanf("%d",&n);
	for(int i=1;i<n;i++)
	scanf("%d",d+i);
	a[0]=0;
	int mi=0;
	int flag=1;
	for(int i=1;i<n;i++)
	{
		a[i]=a[i-1]+d[i];
		mi=min(mi,a[i]);
		if(mi<-500000)
		{
			flag=0;
			break;
		}
	}
	if(!flag)
	{
		printf("-1\n");  
		return 0;
	}
	for(int i=0;i<n;i++)
	a[i]=a[i]-mi+1;
	
	memset(vis,0,sizeof(vis));
	for(int i=0;i<n;i++)
	{
		vis[a[i]]++;
		if(vis[a[i]]>1||a[i]>n)
		{
			flag=0;
			break;
		}
	}
	if(flag)
	{
		for(int i=0;i<n;i++) 
   	    printf("%d ",a[i]);
   	    printf("\n");
	}
    else
    printf("-1\n");    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值