UVA10004 - Bicoloring

来源:互联网 发布:经济学家何帆 知乎 编辑:程序博客网 时间:2024/05/18 03:21

这个题目刚开始想暴力干,可是WA,后来就用了深度搜索算法来实现,主要是通过DFS来搜索和他相邻的边从而得出结果

AC代码

#include<stdio.h>#include<memory.h>#include<algorithm>#include<iostream>#include<string.h>using namespace std;int node,edge;const int maxn=300;int vis[maxn];int color[maxn];int map[maxn][maxn];int ok;void init(){   memset(vis,0,sizeof(vis));   memset(color,0,sizeof(color));   memset(map,0,sizeof(map));}void dfs(int v){   for(int i=0;i<node;i++)   {      if(map[v][i]==1)//假设两个连接的       {         if(!vis[i])         {           vis[i]=1;           color[i]=!color[v];           dfs(i);         }         else         {           if(color[v]==color[i])//错误的连接            {             ok=1;             return;           }         }      }   }}int main(void){    while(scanf("%d",&node)!=EOF)    {      if(node==0) break;      init();      ok=0;      scanf("%d",&edge);      for(int i=0;i<edge;i++)      {        int a,b;        scanf("%d %d",&a,&b);        map[a][b]=map[b][a]=1;      }      vis[0]=1;      dfs(0);      if(ok)        printf("NOT BICOLORABLE.\n");      else          printf("BICOLORABLE.\n");    }    return 0;}


0 0
原创粉丝点击