图着色问题 (25分)

在这里插入图片描述

输入样例:

6 8 3
2 1
1 3
4 6
2 5
2 4
5 4
5 6
3 6
4
1 2 3 3 1 2
4 5 6 6 4 5
1 2 3 4 5 6
2 3 4 2 3 4

输出样例:

Yes
Yes
No
No

思路:

基本思路就是DFS,检查是否有染色违规的。很坑的是出现的颜料种数大于K,也违规。所以要用一个count计数,遇到新出现的颜色就count++.

源码

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define Max 5000
typedef struct Gnode *Graph;
struct Gnode{
	int Nv;
	int Ne;
	int G[Max][Max];
	int color[Max];
};
Graph Creat(void)
{
	Graph p=(Graph)malloc(sizeof(struct Gnode));
	p->Nv=0;
	p->Ne=0; 
	return p;
}
void Insert(Graph MGraph,int a,int b)
{
	MGraph->G[a][b]=1;
	MGraph->G[b][a]=1;
}
int DFS_color(Graph MGraph,int *Visited,int Vertex)
{
	Visited[Vertex]=1;
	int i,j;
	 for(i=1;i<=MGraph->Nv;i++)
	 {
	 	for(j=1;j<=MGraph->Nv;j++)
	 	{
	 		if(MGraph->G[i][j]&&MGraph->color[i]==MGraph->color[j])
	 		{
	 			return 0;
			}
		}
	 } 
	 return 1;
}
void judge_Ok(Graph MGraph,int K)
{
	int i,j;
	int count=0;
	/*count记录当前颜色的个数*/ 
	for(i=1;i<=MGraph->Nv;i++)
	{
		scanf("%d",&MGraph->color[i]);
		
		int f=1;
		for(j=1;j<i;j++)
		{
			if(MGraph->color[i]==MGraph->color[j])
			{
				f=0;break;
			}
		}
		/*f==1说明是一种新出现的颜色,count++;*/ 
		 if(f)count++;
	}
	/*当颜色数目 count > K 时违规,方案不可行 */ 
	if(count!=K)
	{
		printf("No\n");
		return ;
	}
	
	int Visited[MGraph->Nv+1];
	for(i=0;i<=MGraph->Nv;i++)
	Visited[i]=0;
	
	int flag=DFS_color(MGraph,Visited,1);
	
	if(flag)printf("Yes\n");
	else printf("No\n");
}
int main()
{
	Graph MGraph=Creat();
	int V,E,K;
	scanf("%d%d%d",&V,&E,&K);
	MGraph->Ne=E;
	MGraph->Nv=V;
	int i,v1,v2;
	for(i=0;i<E;i++)
	{
		scanf("%d%d",&v1,&v2);
		Insert(MGraph,v1,v2);
	}
	int N;
	scanf("%d",&N);
	for(i=0;i<N;i++)
	{
		judge_Ok(MGraph,K);
	} 
	
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值