三进制循环 - 题目 - Daimayuan Online Judgehttp://oj.daimayuan.top/problem/556
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1e6 + 10;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
int n;
bool vis[MAXN];
int head[MAXN];
int nxt[MAXN];
int s[MAXN];
int cnt;
int ver[MAXN];
int dp[MAXN][2];
inline void add(int x, int y) {
ver[++cnt] = y;
nxt[cnt] = head[x];
head[x] = cnt;
}
int ans = 0;
void dfs(int p, int fa) {
dp[p][1] = dp[p][0] = 1;
for (int i = head[p]; i; i = nxt[i]) {
int v = ver[i];
if (v == fa)
continue;
dfs(v, p);
if ((s[v] + 1) % 3 == s[p])
dp[p][0] = max(dp[p][0], dp[v][0] + 1);
if ((s[p] + 1) % 3 == s[v])
dp[p][1] = max(dp[p][1], dp[v][1] + 1);
}
ans = max(ans, dp[p][1] + dp[p][0] - 1);
}
int main() {
scanf("%d", &n);
int x, y;
for (int i = 1; i < n; i++) {
scanf("%d %d", &x, &y);
add(x, y);
add(y, x);
}
for (int i = 1; i <= n; i++)
scanf("%d", s + i);
dfs(1, 0);
printf("%d", ans);
return 0;
}