题目大意
有一个单调栈,你需要往里面放 nnn 个数,这些数是一个排列。你要保证,放入第 ppp 个数的时候单调栈的大小为 xxx
解题思路
对于没有指定大小的地方,我们可以认为此时的大小为前一个位置大小加一,即b[i]=b[i−1]+1b[i] = b[i-1] + 1b[i]=b[i−1]+1,显然,我们后面一个数不能与前一个数之差大于1,这样会导致中间缺少元素可放,最后我们倒着模拟一遍栈即可得出答案。
Code
#include <bits/stdc++.h>
#define ll long long
#define qc ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
#define fi first
#define se second
#define PII pair<int, int>
#define PLL pair<ll, ll>
#define pb push_back
using namespace std;
const int MAXN = 2e6 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll mod = 1e9 + 7;
inline int read()
{
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
int st[MAXN], b[MAXN];
int ans[MAXN];
void solve(){
int n, k;
cin >> n >> k;
for(int i = 1; i <= k; i++){
int p, x;
cin >> p >> x;
b[p] = x;
}
for(int i = 1; i <= n; ++i){
if(!b[i]) b[i] = b[i-1] + 1;
}
for (int i = 1; i <= n-1; ++i){
if(b[i+1] - b[i] > 1){
cout << -1 << endl;
return;
}
}
int cnt = 0, tot = 0;
for(int i = n; i >= 1; --i){
while(b[i] > tot) st[++tot] = ++cnt;
ans[i] = st[tot--];
}
for(int i = 1; i <= n; ++i)
cout << ans[i] << " ";
cout << endl;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
qc;
int T;
// cin >> T;
T = 1;
while(T--){
solve();
}
return 0;
}
该博客介绍了如何使用单调栈解决一类数组排列问题。在保证单调性的前提下,需要在特定位置插入元素,使得栈在某一位置的大小符合要求。文章通过代码展示了具体的解题过程,包括栈的操作和模拟,最后验证了栈的正确性。
202

被折叠的 条评论
为什么被折叠?



