-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path756d.cpp
More file actions
89 lines (71 loc) · 1.48 KB
/
756d.cpp
File metadata and controls
89 lines (71 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using vpi = vector<pi>;
using vb = vector<bool>;
void solve() {
ll n;
cin >> n;
vi a(n);
ll root = 0;
for (ll i = 0; i < n; i++) {
cin >> a[i];
a[i]--;
if (a[i] == i) root = i;
}
vector<set<ll>> ed(n);
for (ll i = 0; i < n; i++) {
if (i == root) continue;
ed[a[i]].insert(i);
}
vi p(n);
map<ll, ll> mp;
for (ll i = 0; i < n; i++) {
cin >> p[i];
p[i]--;
mp[p[i]] = i;
}
auto compare = [&](ll x, ll y) {
return mp[x] > mp[y];
};
priority_queue<ll, vector<ll>, decltype(compare)> pq(compare);
pq.push(root);
ll i = 0;
vi sum(n);
vi edw(n);
while(!pq.empty()) {
ll top = pq.top();
pq.pop();
if(top != p[i]) {
cout << -1 << endl;
return;
}
if(top != root) {
ll par = sum[a[top]];
if(i - par <= 0) {
cout << -1 << endl;
return;
}
sum[top] = i;
edw[top] = i - par;
}
for(ll child : ed[top]) {
pq.push(child);
}
i++;
}
for(ll w : edw) {
cout << w << " ";
}
cout << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin >> t;
while(t--) solve();
return 0;
}