优化连边然后拓排.

#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
#define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;})
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;}
//head #ifdef ONLINE_JUDGE
const int N = 1e6+10;
#else
const int N = 111;
#endif int n, num, ok, no, a[N], b[N], inq[N<<2];
int val[N<<2], deg[N<<2], vis[N<<2];
vector<int> g[N<<2];
queue<int> q;
void add(int x, int y) {
g[x].pb(y),++deg[y];
}
int build(int o, int l, int r) {
if (l==r) return val[o]=l;
val[o]=++num, g[num].clear(), deg[num]=vis[num]=0;
add(val[o],build(ls)),add(val[o],build(rs));
return val[o];
}
void upd(int o, int l, int r, int ql, int qr, int x) {
if (ql<=l&&r<=qr) return add(x,val[o]);
if (mid>=ql) upd(ls,ql,qr,x);
if (mid<qr) upd(rs,ql,qr,x);
}
void dfs(int x) {
if (vis[x]) return;
vis[x] = inq[x] = 1;
for (int y:g[x]) {
if (inq[y]) ok = 1;
else dfs(y);
}
if (x<=n) b[x]=++no;
inq[x] = 0;
} int main() {
int t;
scanf("%d", &t);
REP(i,1,t) {
scanf("%d", &n);
REP(i,1,n) g[i].clear();
REP(i,1,n) scanf("%d",a+i),g[i].clear(),deg[i]=vis[i]=0;
if (a[n]!=-1&&a[n]!=n+1) {puts("-1");continue;}
num=n,build(1,1,n);
REP(i,1,n-1) if (a[i]!=-1) {
if (a[i]!=i+1) upd(1,1,n,i+1,a[i]-1,i);
if (a[i]!=n+1) add(a[i],i);
}
ok = no = 0;
REP(i,1,num) if (!deg[i]) dfs(i);
if (ok) {puts("-1");continue;}
REP(i,1,n) printf("%d ", b[i]);hr;
}
}
05-04 02:14