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

31 篇文章 0 订阅

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

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

#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<<j<<endl;
		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<<root<<endl;
	dfs(root,-1,0,maxn);
	for(int i=1;i<=n-1;i++)
	{
		printf("%d\n",ans[i]+1);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值