题意:通过栈输出1到n的一组排列,要求字典序最大。题目给出了前k个数,若无解输出-1。
分析:模拟... 好像没啥好说的吧...
代码如下:
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
const int maxn = 200000+10;
int n,k,cnt,mx;
int a[maxn];
stack<int>s;
bool judge(){
cnt = 0;
while (!s.empty()) s.pop();
s.push(a[1]);
for (int i=2; i<=k; i++){
if (s.top()>a[i]) s.push(a[i]);
else {
while (!s.empty() && s.top()<a[i]){
if (s.top()-cnt!=1) return 0;
cnt++;
s.pop();
}
s.push(a[i]);
}
}
while (!s.empty() && s.top()-cnt==1 ) {
cnt++;
s.pop();
}
return 1;
}
inline int Max(int x, int y){return x>y?x:y; }
int main(){
while (scanf("%d %d",&n,&k)==2){
mx = -1;
for (int i=1; i<=k; i++) {
scanf("%d",&a[i]);
mx = Max(mx,a[i]);
}
if (!judge()) printf("-1\n");
else {
while (!s.empty()) {
int num = s.top();
while (num>cnt+1) {
a[++k] = --num;
}
cnt = s.top();
s.pop();
}
if (mx < n) {
for (int i=n; i>=mx+1; i--) a[++k] = i;
}
for (int i=1; i<n; i++) printf("%d ",a[i]);
printf("%d\n",a[n]);
}
}
return 0;
}