首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >codeforces 902B(dfs)

codeforces 902B(dfs)

作者头像
dejavu1zz
发布2020-10-23 15:21:44
2510
发布2020-10-23 15:21:44
举报

题意描述

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

思路

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

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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-07-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意描述
  • 思路
  • AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档