QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#504458 | #9110. Zayin and Tree | untitledtwo# | AC ✓ | 133ms | 20624kb | C++20 | 1.5kb | 2024-08-04 13:15:12 | 2024-08-04 13:15:13 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
struct Edge
{
int to, nxt;
} e[2000010];
int ecnt = 0, head[1000010];
inline void addedge(int from, int to)
{
e[ecnt].to = to;
e[ecnt].nxt = head[from];
head[from] = ecnt++;
}
int a[1000010], dep[1000010], r[1000010], l[1000010], ans = 0;
inline void dfs(int u, int fa)
{
r[u] = dep[u] - a[u], l[u] = dep[u] + a[u];
int mnr = INT_MAX >> 2, smnr = INT_MAX >> 2, mnl = INT_MAX >> 2, smnl = INT_MAX >> 2;
for(int i = head[u]; i != -1; i = e[i].nxt)
{
int v = e[i].to;
if(v == fa)
continue;
dep[v] = dep[u] + 1;
dfs(v, u);
r[u] = min(r[u], r[v]), l[u] = min(l[u], l[v]);
if(r[v] < mnr)
smnr = mnr, mnr = r[v];
else if(r[v] < smnr)
smnr = r[v];
if(l[v] < mnl)
smnl = mnl, mnl = l[v];
else if(l[v] < smnl)
smnl = l[v];
}
int res = INT_MAX;
for(int i = head[u]; i != -1; i = e[i].nxt)
{
int v = e[i].to;
if(v == fa)
continue;
int m = (l[v] == mnl ? smnl : mnl);
res = min(res, r[v] + m);
res = min(res, r[v] + dep[u] + a[u]);
res = min(res, l[v] + dep[u] - a[u]);
}
ans = min(ans, res - dep[u] * 2 + 1);
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
head[i] = -1;
ecnt = 0;
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for(int i = 1; i < n; i++)
{
int u, v;
scanf("%d %d", &u, &v);
addedge(u, v), addedge(v, u);
}
ans = 1;
dep[1] = 1;
dfs(1, 1);
printf("%d\n", ans);
}
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 133ms
memory: 20624kb
input:
3009 5 4 5 3 4 2 1 2 2 3 3 4 3 5 5 4 4 1 1 2 1 2 2 3 3 4 3 5 10 5 8 1 0 8 7 5 2 0 4 2 4 3 8 3 9 1 2 1 3 3 6 4 5 5 7 6 10 10 6 8 8 4 8 0 6 6 0 2 7 10 1 7 2 9 2 3 3 4 1 5 1 6 6 8 1 2 10 9 0 4 0 4 6 0 2 0 0 1 5 1 3 1 7 2 6 1 2 1 9 1 4 5 8 7 10 10 8 8 1 2 7 4 8 6 0 8 1 6 1 7 1 5 7 9 1 3 1 2 2 10 3 4 1 8...
output:
0 -1 -6 -6 -7 -6 -7 -4 -3 -7 -5 -6 -5 -4 -6 -3 -4 -7 -4 -4 -6 -6 -6 -5 -4 -5 -6 -6 -7 -7 -5 -7 -6 -6 -7 -6 -5 -5 -4 -6 -6 -5 -6 -6 -6 -6 -3 -6 -3 -6 -4 -6 -7 -6 -7 -6 -6 -5 -7 -6 -4 -7 -3 -5 -5 -6 -4 -5 -7 -6 -5 -5 -4 -3 -5 -3 -4 -2 -6 -5 -7 -4 -5 -5 -7 -7 -4 -6 -5 -4 -6 -5 -5 -6 -3 -6 -7 -7 -7 -6 -...
result:
ok 3009 lines