QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#605115#9110. Zayin and Treejiangzhihui#AC ✓152ms16284kbC++141.6kb2024-10-02 15:33:422024-10-02 15:33:42

Judging History

你现在查看的是最新测评结果

  • [2024-10-02 15:33:42]
  • 评测
  • 测评结果:AC
  • 用时:152ms
  • 内存:16284kb
  • [2024-10-02 15:33:42]
  • 提交

answer

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f3f3f3f3f;
const int N=1e6+5;
struct graph{
    int head[N],nxt[N<<1],to[N<<1],cnt;
    graph():cnt(1){}
    void add(int u,int v){
        nxt[++cnt]=head[u];
        to[cnt]=v;
        head[u]=cnt;
    }
}gr;
int n,a[N];
void clear(){
    gr.cnt=1;
    for(int i=1;i<=n;i++){
        gr.head[i]=0;
    }
}
ll f[N][2],g[N];
void dfs1(int u,int fa){
    f[u][0]=f[u][1]=inf;
    for(int i=gr.head[u];i;i=gr.nxt[i]){
        int v=gr.to[i];
        if(v==fa)continue;
        dfs1(v,u);
        ll t=min((ll)a[v]+1,f[v][0]+1);
        if(t<f[u][0]){
            f[u][1]=f[u][0];
            f[u][0]=t;
        }else if(t<f[u][1]){
            f[u][1]=t;
        }
    }
}
void dfs2(int u,int fa){
    if(!fa)g[u]=inf;
    for(int i=gr.head[u];i;i=gr.nxt[i]){
        int v=gr.to[i];
        if(v==fa)continue;
        ll t=min((ll)a[v]+1,f[v][0]+1);
        g[v]=min(g[u]+1,(ll)a[u]+1);
        if(t!=f[u][0]){
            g[v]=min(g[v],f[u][0]+1);
        }else{
            g[v]=min(g[v],f[u][1]+1);
        }
        dfs2(v,u);
    }
}
void solve(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    for(int i=1;i<n;i++){
        int u,v;
        cin>>u>>v;
        gr.add(u,v);
        gr.add(v,u);
    }
    dfs1(1,0);
    dfs2(1,0);
    ll ans=1;
    for(int i=1;i<=n;i++){
        ans=min(ans,-a[i]+min(f[i][0],g[i])+1);
    }
    cout<<ans<<'\n';
    clear();
}
int main(){
    ios::sync_with_stdio(false);
    int T;
    cin>>T;
    while(T--){
        solve();
    }
    return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 152ms
memory: 16284kb

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