QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#810013 | #7216. Boxes on tree | eggegg185 | WA | 0ms | 4036kb | C++14 | 1020b | 2024-12-11 19:07:38 | 2024-12-11 19:07:39 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
int n,p[5005],fa[5005],deg[5005]; vector<int> vec[5005];
void dfs(int now,int pa) {
fa[now] = pa; for(auto v:vec[now]) {
if(v == pa) continue; dfs(v,now);
}
} int pa[5005]; int find(int x) {return (x==pa[x])?(x):(pa[x]=find(pa[x]));}
int solve() {
cin >> n; for(int i = 1; i <= n; i++) cin >> p[i],pa[i] = i,deg[i] = 0;
for(int i = 1; i <= n; i++) pa[find(p[i])] = find(i);
for(int i = 1; i < n; i++) {
int u,v; cin >> u >> v;
vec[u].push_back(v); vec[v].push_back(u);
} int ans = 0;
for(int i = 1; i <= n; i++) {
dfs(i,0); int x = p[i]; ans--;
while(x) {ans++; if(find(x) != find(i)) deg[find(x)]++; x = fa[x];}
} for(int i = 1; i <= n; i++) vec[i].clear(),ans += 2*(pa[i]==i)*(!deg[i])*(p[i]!=i);
printf("%d\n",ans-2*(!deg[find(1)])*(p[1]!=1));
return 0;
}
int main() {
//freopen("classic.in","r",stdin); freopen("classic.out","w",stdout);
cin.tie(0)->sync_with_stdio(false);
int T; T = 1; while(T--) solve();
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 0ms
memory: 4032kb
input:
3 1 3 2 1 2 2 3
output:
4
result:
ok 1 number(s): "4"
Test #2:
score: 0
Accepted
time: 0ms
memory: 3944kb
input:
4 2 1 4 3 1 3 3 2 3 4
output:
6
result:
ok 1 number(s): "6"
Test #3:
score: 0
Accepted
time: 0ms
memory: 3920kb
input:
1 1
output:
0
result:
ok 1 number(s): "0"
Test #4:
score: 0
Accepted
time: 0ms
memory: 3944kb
input:
10 1 6 3 4 5 2 7 8 9 10 10 8 8 6 2 1 6 5 7 6 3 4 5 1 8 9 4 8
output:
8
result:
ok 1 number(s): "8"
Test #5:
score: 0
Accepted
time: 0ms
memory: 3912kb
input:
10 1 3 9 4 5 6 7 8 2 10 7 4 2 1 8 10 1 8 6 5 6 4 9 8 8 6 2 3
output:
10
result:
ok 1 number(s): "10"
Test #6:
score: -100
Wrong Answer
time: 0ms
memory: 4036kb
input:
10 8 2 3 9 5 6 7 1 4 10 5 1 5 8 6 5 3 6 10 8 9 3 7 1 6 2 4 10
output:
18
result:
wrong answer 1st numbers differ - expected: '20', found: '18'