问题 K: Coloring Edges on Tree-------------------------------思维(图着色)

题目描述
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 ·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
题意:
给每个边着色,同一个节点的相邻边颜色不允许重复,问最少要涂多少种颜色

解析:
找到节点连边最大数,以这个节点为根,开始赋值。
颜色数就等连边最大数

#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+1000;
#define x first
#define y second
vector<pair<int,int> > G[N];
int in[N];
int ans[N];
int n,maxn,root;
void dfs(int u,int fa,int c,int num)//自顶向下赋值
{
	for(int i=0;i<G[u].size();i++)
	{
		int j=G[u][i].x;
		if(j==fa) continue;
	//	cout<
		ans[G[u][i].y]=c;
		c=(c+1)%num;
		dfs(j,u,c,num);
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n-1;i++)
	{
		int a,b;
		scanf("%d %d",&a,&b);
		G[a].push_back(make_pair(b,i));
		G[b].push_back(make_pair(a,i));
		in[a]++;in[b]++;
	}
	int pos=0;
	for(int i=1;i<=n-1;i++)
	{
		if(in[i]>maxn)
		{
			maxn=in[i];
			root=i;
		}
	}
	printf("%d\n",maxn);
	//cout<
	dfs(root,-1,0,maxn);
	for(int i=1;i<=n-1;i++)
	{
		printf("%d\n",ans[i]+1);
	}
}

你可能感兴趣的:(思维,图论)