题目描述:
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.
Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.
You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.
It is guaranteed that you have to color each vertex in a color different from 0.
You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).
输入描述
The first line contains a single integer n (2 ≤ n ≤ 104) — the number of vertices in the tree.
The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi means that there is an edge between vertices i and pi.
The third line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ n), where ci is the color you should color the i-th vertex into.
It is guaranteed that the given graph is a tree.
输出描述
Print a single integer — the minimum number of steps you have to perform to color the tree into given colors.
样例输入 1
6
1 2 2 1 5
2 1 1 1 1 1
样例输出 1
3
样例输入 2
7
1 1 2 3 1 4
3 3 1 1 1 2 3
样例输出 2
5
说明
The tree from the first sample is shown on the picture (numbers are vetices' indices):
On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):
On seond step we color all vertices in the subtree of vertex 5 into color 1:
On third step we color all vertices in the subtree of vertex 2 into color 1:
The tree from the second sample is shown on the picture (numbers are vetices' indices):
On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):
On second step we color all vertices in the subtree of vertex 3 into color 1:
On third step we color all vertices in the subtree of vertex 6 into color 2:
On fourth step we color all vertices in the subtree of vertex 4 into color 1:
On fith step we color all vertices in the subtree of vertex 7 into color 3:
翻译: 给你n个点,代表这一棵树有n个节点。第二行内容是建树的关系
从第二个节点开始的节点和父节点(上一个节点)相连,
例如:1 2 2 1 5
代表:节点2和节点1相连,节点3和节点2相连,节点4和节点2相连,节点5和节点1相连,节点6和节点5相连。
第三行内容是需要将各个点涂成的颜色,给这个树涂色,有这么一条原则就是给某一节点涂色,以其为根节点的子树也将变为相应的颜色,我们可以成为一种颜料的溢出,问你最终需要
最少需要涂多少次颜色就可以满足题目要求。
解题思路:本题作为cf的第二题,其实思路不用很难,用不到数据结构,就是一个简单的贪心算法,注意到只有字节点与父节点不同时,才需要更改,才计数
#include<iostream>
using namespace std;
int a[10000];
int fa[10000];
int main(){
int n;
cin>>n;
int count=1;
fa[1]=1;//根节点的父亲节点就是自己
for(int i=2;i<=n;i++){
cin>>fa[i];
}
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
if(a[i]!=a[fa[i]]){
count++;
}
}
cout<<count<<endl;
return 0;
}