题目描述
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)
反思:一开始想复杂了,比队友多卡了一个小时!没有想清楚再做,自己还是太菜了;
思路:最后的插入的数字一定在自己的位置上(a[i]==i),把那个数字拿掉(数字前移),再从后往前推下一个数字同样在自己的位置上本来想的是顺序去找,找出在自己位置上的最大的那个数,结果用这个方法没写好哪里有bug,一直卡;其实从后面找到在自己位置上的一定就是最大的,那么就不用找最大的了;
#include <iostream>
using namespace std;
int main()
{
int a[105]={0};
int c[105]={0};
int n;
int cnt=0;
int CNT=0;
int sign=0;
cin>>n;
int flag=0;
for(int i=1;i<=n;i++) cin>>a[i];
//for(int i=1;i<=n;i++) cout<<a[i];
for(int i=n;i>=1;i--)
{
flag=0;sign=0;
for(int j=n;j>=1;j--){ if(a[j]==j) {sign=j;flag=1;break;} }
if(flag==0){cout<<"-1"<<endl; return 0;}
c[CNT++]=sign;
for(int m=sign;m<=n;m++)///
{
a[m]=a[m+1];
//cout<<a[m]<<' ';
}
//cout<<endl;
}
//cout<<CNT<<endl;
for(int i=CNT-1;i>=0;i--)cout << c[i] << endl;
//cout<<endl;
//for(int i=1;i<=CNT;i++)cout << a[i] << endl;
return 0;
}