zoukankan      html  css  js  c++  java
  • [CF780C]Andryusha and Colored Balloons 题解

    前言

    完了,完了,咕值要没了,赶紧写题解QAQ。

    题意简述

    给相邻的三个节点颜色不能相同的树染色所需的最小颜色数。

    题解

    这道题目很显然可以用深搜。
    考虑题目的限制,如果当前搜索到的点为u,
    显然u的父亲节点,u本身和u的所有儿子不能同色(因为兄弟之间相差为2)。
    由于DFS解题,所以搜索到u时,u本身和u的父亲肯定已经有颜色了,那么现在要结局的使u的所有儿子的颜色,那么根据贪心的思想对于每个u的儿子,颜色能往小取就往小取,在选取颜色的时候应当注意,选取的颜色不能与u和u的父亲节点的颜色相同。
    最后的答案就是DFS中使用过的最大的颜色。

    代码

    去掉fread快读其实很短

    #include <cstdio>
    #include <algorithm>
    
    using namespace std; 
    
    namespace fast_IO{
        const int IN_LEN = 10000000, OUT_LEN = 10000000;
        char ibuf[IN_LEN], obuf[OUT_LEN], *ih = ibuf + IN_LEN, *oh = obuf, *lastin = ibuf + IN_LEN, *lastout = obuf + OUT_LEN - 1;
        inline char getchar_(){return (ih == lastin) && (lastin = (ih = ibuf) + fread(ibuf, 1, IN_LEN, stdin), ih == lastin) ? EOF : *ih++;}
        inline void putchar_(const char x){if(oh == lastout) fwrite(obuf, 1, oh - obuf, stdout), oh = obuf; *oh ++= x;}
        inline void flush(){fwrite(obuf, 1, oh - obuf, stdout);}
        int read(){
            int x = 0; int zf = 1; char ch = ' ';
            while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar_();
            if (ch == '-') zf = -1, ch = getchar_();
            while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar_(); return x * zf;
        }
        void write(int x){
            if (x < 0) putchar_('-'), x = -x;
            if (x > 9) write(x / 10);
            putchar_(x % 10 + '0');
        }
    }
    
    using namespace fast_IO;
    
    struct Edge{
        int to, next;
    } edges[400005];
    
    int head[200005], edge_num = 0;
    
    inline void addEdge(int u, int v){
        edges[++edge_num] = (Edge){v, head[u]};
        head[u] = edge_num;
    }
    
    int clr[200005];
    int ans = 0;
    
    void DFS(int u, int fa){
    	int v, cnt = 1;
    	for (int c_e = head[u]; c_e; c_e = edges[c_e].next){
    		v = edges[c_e].to;
    		if (v != fa){
    			while (cnt == clr[u] || cnt == clr[fa])
    				++cnt;
    			clr[v] = cnt++;
    			DFS(v, u);
    		}
    	}
    	ans = max(ans, cnt - 1);
    }
    
    int main(){
    	int n = read();
    	for (int i = 1; i < n; ++i){
    		int u = read(), v = read();
    		addEdge(u, v), addEdge(v, u);
    	}
    	clr[1] = 1; DFS(1, 1);
    	write(ans); putchar_('
    ');
    	for (int i = 1; i <= n; ++i)
    		write(clr[i]), putchar_(' ');
    	flush(); return 0;
    } 
    
  • 相关阅读:
    26 转义符 re模块 方法 random模块 collection模块的Counter方法
    25 正则表达式
    24 from 模块 import 名字
    24 from 模块 import 名字
    24 from 模块 import 名字
    23 析构方法 items系列 hash方法 eq方法
    21 isinstance issubclass 反射 _str_ _new_ _len_ _call_
    20 属性, 类方法, 静态方法. python2与python3的区别.
    python(1)
    python之字符串格式化
  • 原文地址:https://www.cnblogs.com/linzhengmin/p/11298270.html
Copyright © 2011-2022 走看看