codeforces 902B(dfs)

时间:2022-07-28
本文章向大家介绍codeforces 902B(dfs),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

给你一棵树,要求给树染色,给树的一个父结点染色时,该父结点的所有子结点也会被染成同样的颜色,给你颜色列表,求将树染成该列表所用的最小的次数

思路

遍历树的层次,依次进行染色并统计染色的次数

AC代码

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=10100;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int n;
int c[N],now[N];
bool st[N];
vector<int> g[N];
int dfs(int node){
    int res=0;
    st[node]=1;
    if(now[node]!=c[node]){
        res++;
        now[node]=c[node];
    }
    for(auto t : g[node]){
        if(!st[t]){
            now[t]=now[node];
            res+=dfs(t);
        }
    }
    return res;
}
void solve(){
    int n;cin>>n;
    for(int i=2;i<=n;i++){
        int x;cin>>x;
        g[x].push_back(i);
        g[i].push_back(x);
    }
    for(int i=1;i<=n;i++) cin>>c[i];
    cout<<dfs(1)<<endl;
}
int main(){
    IOS;
    solve();
    return 0;
}