QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#569766#9110. Zayin and TreeSGColin#AC ✓385ms48528kbC++171.6kb2024-09-17 10:27:072024-09-17 10:27:10

Judging History

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

  • [2024-09-17 10:27:10]
  • 评测
  • 测评结果:AC
  • 用时:385ms
  • 内存:48528kb
  • [2024-09-17 10:27:07]
  • 提交

answer

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

inline ll rd() {
	ll x = 0;
	bool f = 0;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) f |= (c == '-');
	for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
	return f ? -x : x;
}

#define eb emplace_back
#define all(s) (s).begin(), (s).end()
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define per(i, a, b) for (int i = (a); i >= (b); --i)

const int maxn=1e6+10;

int n,C,ans,a[maxn];
int ma[maxn],siz[maxn],vis[maxn],ansma[maxn],ansmi[maxn];
vector<int>G[maxn];

void get_cen(int u,int fa,int Siz)
{
	siz[u]=1;
	ma[u]=-1;
	for(auto v:G[u])
	{
		if(v==fa||vis[v]) continue;
		get_cen(v,u,Siz);
		siz[u]+=siz[v];
		ma[u]=max(ma[u],siz[v]);
	}
	ma[u]=max(ma[u],Siz-siz[u]);
	if(C==-1||ma[C]>ma[u]) C=u;
}

void update(int u,int fa,int d)
{
	ansma[u]=d-a[u];
	ansmi[u]=d+a[u];
	siz[u]=1;
	for(auto v:G[u])
	{
		if(v==fa||vis[v]) continue;
		update(v,u,d+1);
		ansma[u]=min(ansma[u],ansma[v]);
		ansmi[u]=min(ansmi[u],ansmi[v]);
		siz[u]+=siz[v];
	}
}

void divide(int u,int Siz)
{
	C=-1;
	get_cen(u,0,Siz);
	vis[C]=1;
	update(C,0,0);
	ans=min(ans,ansma[C]+ansmi[C]+1);
	int nw=C;
	for(auto v:G[nw])
	{
		if(vis[v]) continue;
		divide(v,siz[v]);
	}
}

int main() {
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			G[i].clear();
			vis[i]=0;
		}
		for(int i=1,u,v;i<n;i++)
		{
			scanf("%d%d",&u,&v);
			G[u].push_back(v);
			G[v].push_back(u);
		}
		ans=0x3f3f3f3f;
		divide(1,n);
		printf("%d\n",ans);
	}
	return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 385ms
memory: 48528kb

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