Coloring Edges on Treedfs 着色

问题 K: Coloring Edges on Tree
时间限制: 1 Sec 内存限制: 128 MB Special Judge
[提交] [状态]
题目描述
Given is a tree G with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex ai and Vertex bi.
Consider painting the edges in G with some number of colors. We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.
Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.

Constraints
·2≤N≤105
·1≤ai<bi≤N
·All values in input are integers.
·The given graph is a tree.
输入
Input is given from Standard Input in the following format:

N
a1 b1
a2 b2

aN−1 bN−1

输出
Print N lines.
The first line should contain K, the number of colors used.
The (i+1)-th line (1≤i≤N−1) should contain ci, the integer representing the color of the i-th edge, where 1≤ci≤K must hold.

If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.
样例输入 Copy
【样例1】
3
1 2
2 3
【样例2】
8
1 2
2 3
2 4
2 5
4 7
5 6
6 8
【样例3】
6
1 2
1 3
1 4
1 5
1 6
样例输出 Copy
【样例1】
2
1
2
【样例2】
4
1
2
3
4
1
1
2
【样例3】
5
1
2
3
4
5

题目要求给一个图的每个边涂上色,要求到每个点的边颜色不同,问最少要涂多少种颜色和按输入顺序的边的颜色。
比较明显,最少的颜色个数就是度最多的点的度数,让后以任一点为起点dfs挨个涂就OK了。
代码中注释掉的一部分是map存的,都可。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=200010,mod=1e9+7;

int n;
int mx;
int c[N];
int e[N],ne[N],idx,h[N],w[N];
int st;
map<PII,int>mp;
PII edge[N];

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

void dfs(int u,int v,int p)
{
	v++;
	for(int i=h[u];~i;i=ne[i])
	{
		v%=mx;
		
		int j=e[i];
		if(j==p) continue;
		
//		mp[{u,j}]=v,mp[{j,u}]=v;
		w[i]=v;
		dfs(j,v,u);
		v++;
	}
}

int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);

	scanf("%d",&n);
	
	memset(h,-1,sizeof h);
	
	for(int i=1;i<=n-1;i++)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		add(a,b),add(b,a);
//		edge[i]={a,b};
		c[a]++,c[b]++;
		if(c[a]>mx) mx=c[a],st=a;
		if(c[b]>mx) mx=c[b],st=b;
	}

	dfs(1,0,-1);
	
	cout<<mx<<endl;
	
//	for(int i=1;i<=n-1;i++)
//		printf("%d\n",mp[edge[i]]+1);
	for(int i=0;i<idx;i+=2)
	{
		int x=max(w[i],w[i+1]);
		printf("%d\n",x+1);
	}


	return 0;
}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值