我当时是不懂题目是什么意思的,看了别人的才知道原来是所谓的四色问题。我也不知道是什么东东,查了才懂。要学的还有很多呢!太弱了。关键把结构存储进去后,每次遍历它的邻接节点。并把用的颜色标记下来。然后再每次都要遍历每种颜色,如果这种颜色不是邻接的,那么久可以把它给用上。用col[]数组来表示总共用了多少种颜色。好了,代码里也标记得很清楚了。这题还有其它方法,要好好研究研究。 感谢http://blog.csdn.net/lyy289065406。推荐大家看他的博客。
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 9268 | Accepted: 4711 |
Description
Input
Output
Sample Input
2 A: B: 4 A:BC B:ACD C:ABD D:BC 4 A:BCD B:ACD C:ABD D:ABC 0
Sample Output
1 channel needed. 3 channels needed. 4 channels needed.
Source
#include <iostream>
#include <fstream>
using namespace std;
bool vis[27];
int col[27]; //节点对应使用的颜色 col[i]=j.表示节点i使用了颜色j。
typedef class{
public:
int next[27];
int pn;
}point;
int n;
void getmap()
{
}
int main()
{
freopen("acm.txt","r",stdin);
while(scanf("%d",&n) && n)
{
int i,j,maxcolor=1;
memset(col,0,sizeof(col));
point *node=new point[n+1];
for(i=1;i<=n;i++)
{
getchar(); //吸收第一个字母
getchar(); //吸收冒号
if(node[i].pn<0) //初始化指针
node[i].pn=0;
char ch;
while((ch=getchar())!='\n')
{
j=ch%('A'-1); //把结点字母转换为相应的数字,如A->1 C->3
node[i].next[ ++node[i].pn ]=j;
}
}
for(i=1; i<=n; i++)
{
col[i]=n+1;
memset(vis,false,sizeof(vis));
for(j=1; j<=node[i].pn; j++) //判断某种颜色是否被邻接节点使用
{
if(col[node[i].next[j]])
vis[ col[node[i].next[j]] ]=true; //把这种颜色标记一下
}
for(j=1; j<=n; j++) //遍历每种颜色
{
if(!vis[j] && col[i]>j) //某种颜色没有被邻接节点使用
{
col[i]=j;
break;
}
}
if(maxcolor<col[i])
maxcolor=col[i];
}
if(maxcolor==1)
{
printf("%d channel needed.\n",maxcolor);
}
else
{
printf("%d channels needed.\n",maxcolor);
}
delete node;
}
return 0;
}
#include <iostream>
#include <fstream>
#include <memory.h>
using namespace std;
bool map[27][27];
int color[27],color_count;
int n,mincolor,flag;
char s[27];
bool isOK(int dept,int col)
{ //判断某种颜色是否合适
for(int i=1; i<=n ;i++)
{
if(map[dept][i] && color[i]==col)
{
return false;
}
}
return true;
}
void dfs(int depth)
{
if(flag) return;
if(depth==n+1)
{
mincolor=color_count;
flag=1;
}
for(int j=1; j<=color_count; j++) //判断用过的颜色里是否有可用的
{
if(isOK(depth,j))
{
color[depth]=j;
dfs(depth+1);
color[depth]=0;
}
}
//选用一种新的颜色
color_count++;
color[depth]=color_count;
dfs(depth+1);
color[depth]=0;
color_count--;
}
int main(){
freopen("acm.txt","r",stdin);
while(scanf("%d",&n)!=EOF && n)
{
memset(map,0,sizeof(map));
//get the map
for(int i=1; i<=n; i++)
{
getchar();
scanf("%s",s);
for(int j=2; s[j]!='\0'; j++)
map[i][s[j]-'A'+1]=true;
}
mincolor=999; flag=0; color_count=1;
memset(color,0,sizeof(color));
dfs(1);
if(mincolor==1)
printf("%d channel needed.\n",mincolor);
else
printf("%d channels needed.\n",mincolor);
}
return 0;
}