QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#504786#9110. Zayin and TreeXunwuqishi#AC ✓224ms30388kbC++201.6kb2024-08-04 15:58:032024-08-04 15:58:03

Judging History

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

  • [2024-08-04 15:58:03]
  • 评测
  • 测评结果:AC
  • 用时:224ms
  • 内存:30388kb
  • [2024-08-04 15:58:03]
  • 提交

answer

#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) x&(-x)
#define int long long

const int N = 2e6+10;
int ans;

int n,q,ma[N],mi[N],deep[N],lma[N],lmi[N],v[N];
vector<int> to[N];

inline void update(int x,int y)
{
    if(-ma[x] + lma[x] > -ma[y] + lma[y])
	{
        ma[x] = ma[y];
        lma[x] = lma[y];
    }

    if(mi[x] + lmi[x] > mi[y] + lmi[y])
	{
        mi[x] = mi[y];
        lmi[x] = lmi[y];
    }
}

inline void init(int x,int pre)
{
    ma[x] = v[x];
    mi[x] = v[x];
    lma[x] = deep[x];
    lmi[x] = deep[x];

    for(auto i : to[x])
	{
        if(i == pre) continue;
        deep[i] = deep[x] + 1;
        init(i,x);
    }

}

inline void dfs(int x,int pre)
{
    for(auto i : to[x])
	{
        if(i == pre) continue;
        dfs(i,x);
        update(x,i);
    }
    ans = min(ans,-ma[x] + mi[x] + lma[x] - deep[x] + lmi[x] - deep[x] + 1);
}

inline void solve() 
{
    cin>>n;

    for(int i = 1;i<=n;i++) cin>>v[i];
    for(int i = 0;i <= n + 1;i++) 
    {
    	deep[i] = 0;
    	ma[i] = 0;
    	mi[i] = 0;
    	lma[i] = 0;
    	lmi[i] = 0;
	}
    for(int i = 0;i<= n + 1;i++) to[i].clear();

    for(int i = 1;i<n;i++){
        int u,v;
        cin>>u>>v;
        to[u].push_back(v);
        to[v].push_back(u);
    }
    ans = 2e18;
    init(1,0);
    dfs(1,0);

    cout<<ans<<endl;

}
signed main() {
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    //cout<<fixed<<setprecision(8);
    int caset = 1;
    cin>>caset;

    for(int i = 1;i<=caset;i++){
        //cout<<"Case "<<i<<": "<<endl;
		solve();
	}

    return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 224ms
memory: 30388kb

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