首页 > 代码库 > search1129

search1129

一个有N个节点的无向图,要求对每个节点进行染色,使得相邻两个节点颜色都不同,问最少需要多少种颜色?

 

暴力法自己通过的:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;bool map[30][30];int cmpmax(int a,int b){	return a>b;}int main(){	char str[33];	int i,j,num,color_number;	int color[33];	while(scanf("%d",&num),num)	{		memset(map,0,sizeof(map));		memset(color,0,sizeof(color));		color_number=1;				for(i=1;i<=num;i++)		{			scanf("%s",str);			for(j=2;j<=strlen(str)-1;j++)				map[i][str[j]-‘A‘+1]=1;		}				color[1]=1;	    int	cur_color=1;		bool ok;		for(i=2;i<=num;i++)		{			cur_color=1;//对每个节点从第一个颜色开始试,直至成功			ok=0;			while(!ok)			{				color[i]=cur_color++;								for(j=1;j<=num;j++)				{					if(map[i][j]==1 && color[i]==color[j])						break;				}				if(j==num+1)					ok=1;			}		}		sort(color+1,color+30,cmpmax);		if (color[1] == 1)            printf("1 channel needed.\n");        else            printf("%d channels needed.\n", color[1]);	}	return 1;}

  

search1129