养老社区 n遍BFS + 枚举
作者:
徐枭翔
,
2024-08-03 21:43:38
,
所有人可见
,
阅读 2
https://pintia.cn/problem-sets/1556843855285559296/exam/problems/type/7?problemSetProblemId=1556843936151740420&page=0
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;
typedef vector<long long> VI;
//#define int long long
#define INF 0x3f3f3f3f
#define endl '\n'
#define N 2020
const int mod = 1e9 + 7;
int n, t[N];
vector<int> g[N];
int vis[N], e[N][N];
void bfs(int x) {
queue<int> q;
vis[x] = 1;
q.push(x);
while (q.size()) {
auto t = q.front();
q.pop();
for (auto to : g[t]) {
if (vis[to])continue;
vis[to] = 1;
e[x][to] = e[x][t] + 1;
q.push(to);
}
}
}
void solve() {
cin >> n;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
for (int i = 1; i <= n; i ++)cin >> t[i];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j ++)vis[j] = 0;
bfs(i);
}
int res = 0;
for (int i = 1; i <= n; i ++) {
for (int j = i + 1; j <= n; j ++) {
for (int k = j + 1; k <= n; k++) {
if (e[i][j] == e[j][k] && e[i][j] == e[i][k]) {
if (t[i] != t[j] && t[i] != t[k] && t[j] != t[k]) {
res ++;
}
}
}
}
}
cout << res << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T = 1;
// cin >> T;
while (T --)
solve();
return 0;
}