题目描述
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,然后贪心,从后往前,找当前这个数,是不是刚插上的,复杂度N^3
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
int b[110];
int ans[110];
int main() {
int cnt, flag = 0;
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%d", &b[i]);
if(b[i] > i)
flag = 1;
}
if(flag) {
printf("-1\n");
return 0;
}
int len = n;
for(int i = 1; i <= n; i++) {
flag = 0;
for(int j = n; j >= 1; j--) {
if(b[j] == 0) continue;
cnt = 0;
for(int k = 1; k <=j; k++)
if(b[k]) cnt++;
if(cnt == b[j]) {
ans[len] = b[j];
b[j] = 0;
break;
}
}
len--;
}
for(int i = 1; i <= n; i++)
printf("%d\n", ans[i]);
return 0;
}