DAY2.1 Polycarp Restores Permutation

本文介绍了一种算法,帮助解决Polycarp遗忘的排列问题。通过给定的差值序列,该算法能够恢复出原始的整数排列,确保每个数字从1到n恰好出现一次。文中提供了两种实现思路及代码示例。

C. Polycarp Restores Permutation

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
An array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].

Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.

Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.

Input
The first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).

Output
Print the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.

Examples
inputCopy
3
-2 1
outputCopy
3 1 2
inputCopy
5
1 1 1 1
outputCopy
1 2 3 4 5
inputCopy
4
-1 2 2
outputCopy
-1

思考&过程

第一次就想直接模拟,找到符合的就退出,结果第38个点就超时了。
WA代码:

#include<iostream>
using namespace std;

int main()
{
	int n,i,j;
	static int a[200010],b[200010],c[200010];
	cin>>n;
	for(i=1;i<=n-1;i++)
	{
		cin>>a[i];
	}
	bool t;
	t=true;
	i=1;
	while((i<=n)&&(t))
	{
		for(j=1;j<=n;j++) c[j]=0;
		bool tt=true;
		b[1]=i;
		c[b[1]]=1;
		j=2;
		while((j<=n)&&(tt))
		{
			b[j]=b[j-1]+a[j-1];
			if((b[j]<=0)||(b[j]>n)||(c[b[j]]==1)) tt=false;
			c[b[j]]=1;
			j=j+1;
		}
		if (tt) 
		{
			t=false;
			for(int p=1;p<=n;p++) cout<<b[p]<<" ";
		}
		i=i+1;
	}
	if (t) cout<<"-1";
	return 0;
 } 

之后队友提示其实找到第一个无重复就行,然后统一加上差值,就可以使数列落在1-n,AC代码:

#include<iostream>
using namespace std;

int main()
{
	long long ans,n,i,j,minn;
	static int a[200010],b[200010],p[200010];
	cin>>n;
	for(i=1;i<n;i++)
	{
		cin>>a[i];
		p[i]=p[i-1]+a[i];
	}
	minn=p[0];
	for(i=1;i<n;i++)
	{
		if (p[i]<minn) minn=p[i];
	}
	for(i=0;i<n;i++)
	{
		if(p[i]-minn+1>n||b[p[i]-minn+1])
		{
			cout<<"-1"<<endl;
			return 0;
		}
		b[p[i]-minn+1]=1; 
	}
	for(i=0;i<n;i++) cout<<p[i]-minn+1<<" ";
	return 0;
 } 

还有个队友提出这题可以数学解,推出公式可求第一项。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值