QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#504691 | #9110. Zayin and Tree | Folity# | AC ✓ | 483ms | 17660kb | C++20 | 1.6kb | 2024-08-04 14:53:45 | 2024-08-04 14:53:45 |
Judging History
answer
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e6+5,inf=1e9;
int n,a[N],x,y;
vector<int> e[N];
void adde(int x,int y){
e[x].push_back(y);
}
int rt,mw[N],all,sz[N];
bool vis[N];
void dfs1(int u,int f){
sz[u]=1,mw[u]=0;
for(int v:e[u])if(!vis[v]&&(v^f)){
dfs1(v,u);
sz[u]+=sz[v];
mw[u]=max(mw[u],sz[v]);
}
mw[u]=max(mw[u],all-sz[u]);
if(mw[u]<mw[rt])rt=u;
}
int ans;
void dfs3(int u,int f,int mx,int mn,int dis){
ans=min(ans,dis-mx+mn);
for(int v:e[u])if(!vis[v]&&(v^f))
dfs3(v,u,max(mx,a[v]),min(mn,a[v]),dis+1);
}
int lstmx,lstmn;
int curmx,curmn;
void dfs4(int u,int f,int mx,int mn,int dis){
curmx=min(curmx,dis-mx);
curmn=min(curmn,dis+mn);
for(int v:e[u])if(!vis[v]&&(v^f))
dfs4(v,u,max(mx,a[v]),min(mn,a[v]),dis+1);
}
void dfs2(int u){
vis[u]=1;
dfs3(u,0,a[u],a[u],1);
lstmx=inf,lstmn=inf;
for(int v:e[u])if(!vis[v]){
curmx=inf,curmn=inf;
dfs4(v,u,max(a[u],a[v]),min(a[u],a[v]),1);
ans=min(ans,min(lstmx+curmn+1,lstmn+curmx+1));
lstmx=min(lstmx,curmx),lstmn=min(lstmn,curmn);
}
for(int v:e[u])if(!vis[v])
rt=0,all=sz[v],dfs1(v,u),dfs2(rt);
}
void solve(){
cin>>n;
for(int i=1;i<=n;++i)cin>>a[i],e[i].clear();
for(int i=1;i<n;++i){
cin>>x>>y;
adde(x,y),adde(y,x);
}
ans=1e9;
rt=0,all=n,mw[0]=n+1;
memset(vis,0,sizeof(bool)*(n+1));
dfs1(1,0),dfs2(rt);
cout<<ans<<'\n';
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);
int T;
cin>>T;
while(T--)solve();
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 483ms
memory: 17660kb
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