codeforces902B

题目给出一颗有根树,请你输出将这棵树上每个节点v染成对应的颜色Cv,所需要的最少的操作。这棵树的树根是节点1,标号从1到n
染色操作是这样的,选择一个节点v和颜色x,一次染色操作会把节点v所在的子树的所有节点都染成x。

Input

第一行是一个整数n代表树的节点个数(2<=n<=10^4)
第二行有n-1个整数p2,p3…pn(1《=pi《i),代表i节点和pi有一条边
第三行有n个整数c1,c2,c3,…cn 代表每个节点需要被染成的颜色
保证数据是一个合法的树

Output

输出最小的步骤

Example

Input

6
1 2 2 1 5
2 1 1 1 1 1

Output

3

Input

7
1 1 2 3 1 4
3 3 1 1 1 2 3

Output

5

这个题我是用bfs写的,直至看到了网上大神们的题解······顿时膜拜!!!

思路是用vector建树,然后从根节点遍历,每经过一次bfs,次数+1

代码如下:

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<functional>
#include<map>
using namespace std;
const int maxn = 15000;
typedef long long ll;
vector<int>vec[maxn];
int vis[maxn];
int n;
int p;
int c;
queue<int>q;
int ans = 0;
void bfs(int n)
{	
	int now = n;
	q.push(now);
	vis[now] = c;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		for (int i = 0; i < vec[now].size(); i++) {
			int tem = vec[now][i];
			if (vis[tem] != c) {
				vis[tem] = c;
				q.push(tem);
			}
		}
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin >> n;
	memset(vis, 0, sizeof(vis));
	for (int i = 2; i <= n; i++) {//建树
		cin >> p;
		vec[p].push_back(i);
		vis[i] = 0;
	}
	for (int i = 1; i <= n; i++) {
		cin >> c;
		if (vis[i] != c)//如果这个点没染色,就广度
		{
			bfs(i);
			ans++;
		}
	}
	cout << ans << endl;
	//system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zsnowwolfy/article/details/82690695