QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#505962#9110. Zayin and TreeWendyChenAC ✓149ms24108kbC++201.0kb2024-08-05 14:13:582024-08-05 14:13:58

Judging History

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

  • [2024-08-05 14:13:58]
  • 评测
  • 测评结果:AC
  • 用时:149ms
  • 内存:24108kb
  • [2024-08-05 14:13:58]
  • 提交

answer

#include <bits/stdc++.h> 
using namespace std;
#define int long long
#define endl '\n'
#define base 191
#define mod 1145141
#define inf 0x3f3f3f3f3f3f3f3f
const int N = 1e7 + 10;
int n;
int ans;
vector<int>edge[1000010];
int a[1000010];
int dep[N], min1[N], min2[N];
void dfs(int u, int fa) {
	min1[u] = a[u] + dep[u];
	min2[u] = -a[u] + dep[u]; 
	for (auto it : edge[u]) {
		if (it == fa) {
			continue;
		}
		dep[it] = dep[u] + 1;
		dfs(it, u);
		min1[u] = min(min1[u], min1[it]);
		min2[u] = min(min2[u], min2[it]);
	}
	ans = min(ans, min1[u] + min2[u] - 2 * dep[u] + 1);
}
void solve() {
	cin >> n;
	ans = inf;
	int ma = 1;
	for (int i = 1; i <= n; ++i) {
		cin >> a[i];
		edge[i].clear();
	}
	for (int i = 1; i <= n - 1; ++i) {
		int u, v;
		cin >> u >> v;
		edge[u].push_back(v);
		edge[v].push_back(u);
	}
	dfs(1, 0);
	cout << ans << endl;
}

signed main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	int T = 1;
	cin >> T;
	while (T--) {
		solve();
		
	}
}

/*2
3
1 1
1 3 2
3
1 2
1 3 2*/

详细

Test #1:

score: 100
Accepted
time: 149ms
memory: 24108kb

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