• codeforces902B. Coloring a Tree


    B. Coloring a Tree

    题目链接:

    https://codeforces.com/contest/902/problem/B

    题意:给你一颗树,原先是没有颜色的,需要你给树填色成指定的样子,每次填色的话,子树会和根节点变成同一种颜色,问需要多少次填色

    题解:前向星建树,从每个父节点便利,如果父节点的颜色和子节点不一样就ans++吗,最后记得把第一次操作(根节点涂色的次数 给记上

    代码如下:

    #include <map>
    #include <set>
    #include <cmath>
    #include <ctime>
    #include <stack>
    #include <queue>
    #include <cstdio>
    #include <cctype>
    #include <bitset>
    #include <string>
    #include <vector>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #include <functional>
    #define fuck(x) cout<<"["<<x<<"]";
    #define FIN freopen("input.txt","r",stdin);
    #define FOUT freopen("output.txt","w+",stdout);
    //#pragma comment(linker, "/STACK:102400000,102400000")
    using namespace std;
    typedef long long LL;
    typedef pair<int, int> PII;
    const int maxn = 3e5+5;
    const int INF = 0x3f3f3f3f;
    const int MOD = 1e9+7;
    int cnt;
    int head[maxn],nxt[maxn],to[maxn];
    int color[maxn];
    int ans;
    void add(int x,int y){
        to[cnt]=y;
        nxt[cnt]=head[x];
        head[x]=cnt++;
    }
    
    int main(){
    #ifndef ONLINE_JUDGE
        FIN
    #endif
        int n,x;
        cnt=1;
        memset(head,-1,sizeof(head));
        scanf("%d",&n);
        for(int i=2;i<=n;i++){
            scanf("%d",&x);
            add(x,i);
        }//前向星连边
        for(int i=1;i<=n;i++){
            scanf("%d",&color[i]);
        }
        for(int i=1;i<=n;i++){
            for(int j=head[i];j!=-1;j=nxt[j]){
                //如果父节点和子树的节点不一样就操作一次
                if(color[i]!=color[to[j]]) ans++;
            }
        }
        cout<<ans+1<<endl; //根节点的第一次操作算进去
    
    }
    View Code
    每一个不曾刷题的日子 都是对生命的辜负 从弱小到强大,需要一段时间的沉淀,就是现在了 ~buerdepepeqi
  • 相关阅读:
    谈谈SpringFramework与IoC依赖查找
    监控微博、论坛的“棱镜计划”
    输出质数的方法改进
    参数解构
    直接插入排序
    理解迭代
    异常处理
    函数
    continue语句
    break语句
  • 原文地址:https://www.cnblogs.com/buerdepepeqi/p/9478176.html
Copyright © 2020-2023  润新知