CodeForces 804C :Ice cream coloring dfs + 染色

传送门

题目描述

含有n个节点的树,每个节点含有si个冰淇凌,这si个冰淇凌构成一个完全图,这个完全图的各个冰淇凌的颜色不能相同,也就是说相邻的冰淇凌颜色不同。问最少需要几种颜色可以将G染色。

分析

我们可以先把第一个点的所有冰淇凌进行染色,然后dfs到下一个点,如果这个点中,已经有冰淇凌被染色,那么重新分配颜色,然后继续dfs到下一个点

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#include <set>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 3e5 + 10,M = N * 2;
set<int> col[N];
int n,m;
int res;
int h[N],ne[M],e[M],idx;
int ans[N];

void add(int x,int y){
    
    
	ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}

void dfs(int u,int fa){
    
    
	vector<int> back;
	for(auto t:col[u])
		if(ans[t]) 
			back.push_back(ans[t]);
	sort(back.begin(), back.end());

	if(fa == -1){
    
    
	    for(auto t:col[u]){
    
    
	        ans[t] = ++res;
	    }
	}
	else{
    
    
    	int l = 0,p = 1;
    	for(auto t:col[u]){
    
    
    		if(!ans[t]){
    
    
    			while(l < back.size()){
    
    
    				if(p == back[l]) l++,p++;
    				else break;
    			}
    			ans[t] = p++;
    		}
    		res = max(res,p - 1);
    	}
	}
	for(int i = h[u];~i;i = ne[i]){
    
    
		int j = e[i];
		if(j == fa) continue;
		dfs(j,u);
	}
}

int main(){
    
    
    scanf("%d%d",&n,&m);
    for(int i = 0;i <= n;i++){
    
    
        h[i] = -1;
    }
    for(int i = 1;i <= n;i++){
    
    
    	int num;
    	scanf("%d",&num);
    	while(num--){
    
    
    		int x;
    		scanf("%d",&x);
    		col[i].insert(x);
    	}
    }
    for(int i = 1;i < n;i++){
    
    
    	int x,y;
    	scanf("%d%d",&x,&y);
    	add(x,y),add(y,x);
    }
    dfs(1,-1);
    res = max(res,1);
    printf("%d\n",res);
    for(int i = 1;i <= m;i++){
    
    
        if(!ans[i]) ans[i] = 1;
    	printf("%d ",ans[i]);
    }
   	return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/

猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/112966865