3 seconds
:256 megabytes
standard output
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.
There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).
To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v andu). For example, consider the tree
and apply operation paint(3) to get the following:
Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.
Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.
Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.
11
0 0 0 1 1 0 1 0 0 1 1
1 2
1 3
2 4
2 5
5 6
5 7
3 8
3 9
3 10
9 11
2
4
0 0 0 0
1 2
2 3
3 4
0
In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.
In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0.
题目链接:http://codeforces.com/contest/734/problem/E
题意:给你一棵黑白树,每次paint(v)操作可以指定任何一个节点v,然后使得这个节点周围的同色连通块变色。问你最少花费多少次,使得整个树都是一个颜色。
思路:因为是同色联通块一起变色,所以把同色联通块缩成一个点。那个就成了一棵黑白相间的树。最少只需要把这棵树的直径(长度为L)的中点变换L/2次。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5+;
int n,c[maxn];
vector<int> G[maxn];
pair<int,int> dfs(int u,int fa,int deep)
{
pair<int,int> tmp=make_pair(deep,u);
for(int i=; i<G[u].size(); i++)
{
int v=G[u][i];
if(v==fa)continue;
if(c[v]!=c[u]) tmp=max(tmp,dfs(v,u,deep+));
else tmp=max(tmp,dfs(v,u,deep));
}
return tmp;
}
int main()
{
scanf("%d",&n);
for(int i=; i<=n; i++)scanf("%d",&c[i]);
for(int i=; i<n; i++)
{
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
pair<int,int> tmp=dfs(,-,);
tmp=dfs(tmp.second,-,);
cout<<tmp.first/<<endl;
}
DFS