题解:AT_agc046_e [AGC046E] Permutation Cover
UKE_Automation · · 题解
AGC046E Permutation Cover
首先先看无解的条件。如果不考虑字典序的话我们有一个非常简单的构造方案:每一次加入一个
然后考虑
所以我们得到了无解的充要条件:当
考虑增量构造,我们每次往当前序列后面加入一个长度
首先在确定
- 若
2\min(a')\ge \max(a') ,那么此时后面必然有解,将S 排序后就是合法序列。 - 若
2\min(a')+1<\max(a') ,根据上面的理论,后面的所有x 最多匹配2\min(a') 个y ,而当前放的最后一个x 最多只能再多匹配一个y 。那么最多匹配上2\min(a')+1 个y ,所以此时必然无解。 - 若
2\min(a')+1=\max(a') ,那么此时我们要尽可能将所有a_x=\min(a') 的x 往后放。更具体的,所有的x 都应该在a_y=\max(a') 的y 的后面。用贪心简单实现即可。
综上我们可以在
#include <bits/stdc++.h>
#define il inline
using namespace std;
const int Maxn = 2e5 + 5;
const int Inf = 2e9;
template <typename T> il void chkmax(T &x, T y) {x = (x >= y ? x : y);}
template <typename T> il void chkmin(T &x, T y) {x = (x <= y ? x : y);}
template <typename T>
il void read(T &x) {
x = 0; char ch = getchar(); bool flg = 0;
for(; ch < '0' || ch > '9'; ch = getchar()) flg = (ch == '-');
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48);
flg ? x = -x : 0;
}
template <typename T>
il void write(T x, bool typ = 1) {
static short Stk[50], Top = 0;
x < 0 ? putchar('-'), x = -x : 0;
do Stk[++Top] = x % 10, x /= 10; while(x);
while(Top) putchar(Stk[Top--] | 48);
typ ? putchar('\n') : putchar(' ');
}
bool Beg;
int n, m, a[Maxn], t[Maxn];
int len, ans[Maxn];
il void chk(vector <int> &res, vector <int> &v) {
for(int i = 0; i < min(v.size(), res.size()); i++) {
if(res[i] != v[i]) {
if(v[i] < res[i]) res = v;
return ;
}
}
if(v.size() < res.size()) res = v;
return ;
}
int vis[Maxn];
vector <int> res;
il void solve(int p) {
vector <int> S;
for(int i = 1; i <= n; i++) vis[i] = 0;
for(int i = len - (n - p) + 1; i <= len; i++) vis[ans[i]] = 1;
for(int i = 1; i <= n; i++) if(!vis[i]) S.push_back(i), a[i]--;
int mn = Inf, mx = 0;
for(int i = 1; i <= n; i++) chkmin(mn, a[i]), chkmax(mx, a[i]);
if(2 * mn + 1 < mx) return ;
if(2 * mn >= mx) return chk(res, S);
S.clear();
for(int i = 1; i <= n; i++) if(!vis[i] && a[i] != mn) S.push_back(i);
while(S.size() && a[S.back()] != mx) S.pop_back();
for(auto p : S) vis[p] = 1;
for(int i = 1; i <= n; i++) if(!vis[i]) S.push_back(i);
chk(res, S);
}
bool End;
il void Usd() {cerr << (&Beg - &End) / 1024.0 / 1024.0 << "MB " << (double)clock() * 1000.0 / CLOCKS_PER_SEC << "ms\n"; }
int main() {
read(n);
for(int i = 1; i <= n; i++) read(a[i]), m += a[i];
int mn = Inf, mx = 0;
for(int i = 1; i <= n; i++) chkmin(mn, a[i]), chkmax(mx, a[i]);
if(2 * mn < mx) {write(-1); return 0;}
while(len < m) {
res.resize(n);
for(int i = 0; i < n; i++) res[i] = Inf;
for(int i = max(n - len, 1); i <= min(m - len, n); i++) {
for(int j = 1; j <= n; j++) t[j] = a[j];
solve(i);
for(int j = 1; j <= n; j++) a[j] = t[j];
}
for(auto p : res) ans[++len] = p, a[p]--;
}
for(int i = 1; i <= len; i++) write(ans[i], 0);
Usd();
return 0;
}