题解:ARC227 - B
题面:Know Your Place。
解题思路
题目中说 是 的一个排列,这也就意味着对于任意 ,序列中小于 的数量是固定的,因此可以想到从小到大处理。
枚举 ,每次处理时,先将所有原序列值为 的放进栈中,此时栈底到栈顶从小到大,从下标 开始,依次把栈顶元素放在已经构造好一部分的序列 的末尾。
这样可以让 为任意 的值:
-
对于 ,因为 都是小于 的值,所以可以;
-
对于 ,令上一个为此值的是 , 中的值均 ,因此也可以。
无解的情况:如果在处理到某一个 时栈空了,那就意味着此时已经没有值 了,而 只处理了 个元素,所以无解。
这样构造的时间复杂度为 ,因为栈中 个元素都只会处理一次。
代码实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <atcoder/all>
#define endl '\n'
using namespace std;
typedef long long ll;
int main(int argc, char* argv[]) {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
int x; cin >> x;
a[x]++;
}
vector<int> ans(n); // 即序列 B
stack<int> stk;
for (int i = 0; i < n; i++) {
for (int j = 0; j < a[i]; j++) {
stk.push(i);
}
if (!stk.empty()) {
ans[i] = stk.top(); stk.pop();
} else { // 无解的情况
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
for (auto& p : ans) {
cout << p << ' ';
}
cout << endl;
return 0;
}