题目描述
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
1
2
提示
In this sequence of operations, the sequence a changes as follows:
·After the first operation: (1)
·After the second operation: (1,1)
·After the third operation: (1,2,1)
思路:插入是有顺序的,那么就每次找最后一个插入的元素,找到后将它删除并存储起来,直到某一次找不到一个数值等于其下标的元素为止,最后比较一下删除掉的那些元素个数是否等于n,若相等,说明找到了一个操作序列,将其倒序输出,否则的话输出-1。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int a[105];
vector<int> ans;
int n,tem;
cin>>n;
tem=n; //n会在后面改变它,所以要先保存一下
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=n;i>=1;i--)
{
if(a[i]==i)
{
ans.push_back(a[i]);
n--;
for(int j=i;j<=n;j++)
a[j]=a[j+1];
i=n+1; //因为此次操作后会将i--,所以要等于n+1
}
}
if(ans.size()==tem)
{
for(int i=ans.size()-1;i>=0;i--)
cout<<ans[i]<<endl;
}
else
cout<<-1<<endl;
return 0;
}