제출 #379818

#제출 시각아이디문제언어결과실행 시간메모리
379818cgiosyMergers (JOI19_mergers)C++17
100 / 100
799 ms78956 KiB
#include <bits/stdc++.h>
using namespace std;

int main() {
	ios::sync_with_stdio(0);cin.tie(0);
	int N, M, ans=0, t=0;
	cin>>N>>M;
	if(N<3) { cout<<M-1<<'\n'; return 0; }

	vector<int> C(N), L(M), R(M);
	vector<vector<int>> G(N);
	for(int i=1; i<N; i++) {
		int x, y;
		cin>>x>>y; --x, --y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
	for(int i=0; i<N; i++) cin>>C[i], --C[i];

	function<void(int, int)> f=[&](int i, int p) {
		++t;
		L[C[i]]=L[C[i]]?:t;
		for(int j:G[i]) if(j!=p) f(j, i);
		R[C[i]]=t;
	};
	f(0, 0);

	t=0;
	function<tuple<int, int, int>(int, int)> g=[&](int i, int p) {
		++t;
		int a=L[C[i]], b=R[C[i]], x=0, s=t;
		for(int j:G[i]) if(j!=p) {
			auto[c,d,y]=g(j, i);
			a=min(a, c);
			b=max(b, d);
			x+=y;
		}
		if(s==a && b==t && i) ans+=!x, x=1;
		return make_tuple(a, b, x);
	};
	int r=get<2>(g(0, 0))==1;
	cout<<(ans+r+1)/2<<'\n';
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...