이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include "bits/stdc++.h"
#define int long long
using namespace std;
const int MAXN = 5e5 + 10;
vector<int> adj[MAXN];
vector<int> adj2[MAXN];
int s[MAXN];
int dsu[MAXN];
int set_of(int u) {
if(dsu[u] == u) return u;
return dsu[u] = set_of(dsu[u]);
}
void union_(int u, int v) {
dsu[set_of(u)] = set_of(v);
}
map<pair<int, int>, bool> lit;
int cnt[MAXN], tot[MAXN];
int r = 0; // Number of colors that are in both sides
void dfs(int node, int prev) {
if(r == 0 && prev != -1) {
lit[{node, prev}] = lit[{prev, node}] = 1;
}
r -= (cnt[s[node]] == 0 || cnt[s[node]] == tot[s[node]] ? 0 : 1);
cnt[s[node]]--;
r += (cnt[s[node]] == 0 || cnt[s[node]] == tot[s[node]] ? 0 : 1);
for(int x: adj[node]) {
if(x != prev) {
dfs(x, node);
}
}
r -= (cnt[s[node]] == 0 || cnt[s[node]] == tot[s[node]] ? 0 : 1);
cnt[s[node]]++;
r += (cnt[s[node]] == 0 || cnt[s[node]] == tot[s[node]] ? 0 : 1);
}
int32_t main() {
int n,k;cin >> n >> k;
for(int i=1;i<n;i++) {
int a,b;cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for(int i=1; i<=n; i++) cin >> s[i];
for(int i=1; i<=n; i++) tot[s[i]]++, cnt[s[i]]++;
for(int i=0; i<=n; i++) dsu[i] = i;
dfs(1, -1);
for(int i=1; i<=n; i++) {
for(int x: adj[i]) {
if(i < x) {
if(!lit[{i, x}]) {
union_(i, x);
}
}
}
}
map<pair<int, int>, bool> mp;
for(int i=1; i<=n; i++) {
for(int x: adj[i]) {
if(set_of(i) != set_of(x) && mp[{set_of(i), set_of(x)}] == 0) {
mp[{set_of(i), set_of(x)}] = 1;
mp[{set_of(x), set_of(i)}] = 1;
adj2[set_of(i)].push_back(set_of(x));
adj2[set_of(x)].push_back(set_of(i));
}
}
}
int s = 0;
for(int i=1; i<=n; i++) {
s += (adj2[i].size() == 1);
}
cout << (s + 1) / 2 << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |