Limited Insertion
题目描述:
Snuke has an empty sequence a.
He will perform N operations on this sequence.
In the i-th operation, he chooses an integer j satisfying 1≤j≤i, and insert j at position j in a (the beginning is position 1).
You are given a sequence b of length N. Determine if it is possible that a is equal to
b after N operations. If it is, show one possible sequence of operations that achieves it.
Constraints
·All values in input are integers.
·1≤N≤100
·1≤bi≤N
输入:
Input is given from Standard Input in the following format:
N
b1 … bN
输出:
If there is no sequence of N operations after which a would be equal to b, print -1. If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.
样例输入:
3
1 2 1
样例输出:
1
2
题目大意:Snuke有一个空序列a。他将对这个序列执行N个操作。在第i次操作中,他选择一个满足1≤j≤i的整数j,将j插入a的位置j(起始位置为1)。给定一个长度为n的序列b,判断a是否可能等于b经过N次运算。如果是,显示一个可能实现它的操作序列,如果不是,输出-1。
思路:从后往前搜,找到第一个i和a[i]对应的数就放入另一个数组里(不能从前往后搜,比如 1,2,3,放入新数组的顺序应该是3,2,1,最后倒序输出),并将其后面的数往前移一位;重新从后往前搜……重复此过程,中间以k记录,若退出循环是k==n,则是可以的,否则不可能达到。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k=0;
cin>>n;
int a[n+1]={0},b[n+1]= {0};
for(int i=1; i<=n; i++)
{
cin>>a[i];
}
int l=1;
for(int i=n;i>=1;)//倒序搜索
{
if(a[i]==i)
{
b[l]=a[i];
l++;
k++;
for(int j=i;j<=n;j++)
{
a[j]=a[j+1];
}
i=n;//搜到了,数组上数的位置改变,从头开始搜
}
i--;
}
if(k==n)
{
for(int i=n;i>=1;i--)
{
printf("%d\n",b[i]);//倒序输出
}
}
else printf("-1\n");
//printf("%d\n",k);
return 0;
}