hrbust 1614 小z的地图 dfs

来源:互联网 发布:python smtp发送邮件 编辑:程序博客网 时间:2024/06/05 00:07

小z的地图Time Limit: 1000 MSMemory Limit: 32768 KTotal Submit: 101(30 users)Total Accepted: 28(24 users)Rating: Special Judge: NoDescription小z有一张被分割成了N块不规则的多边形区域的地图,他将每块多边形区域从1到N依次标号。
他现在想将所有多边形区域涂上颜色,并且让所有相邻的多边形区域颜色不同。小z想知道
最少需要多少种颜色可以将地图涂满。


Input输入第一行为组数T(T<=15)。
对于每组数据第一行为两个整数N和M(1 <= N <= 30)。
分别代表有多边形的数量,以及多边形之间的相邻的数量。
接下来有M个整数对a b。代表多边形a和多边形b相连。Output对于每组数据输出最少需要的颜色数量。Sample Input2
7 9
1 2 1 3 2 3 2 5 3 5 3 4 3 6 4 6 4 7  
5 4
1 2 2 3 3 4 4 5Sample Output3
2Hint已知对于地图着色,最多只需四种颜色即可保证相邻多边形区域颜色不同,并且将地图涂满。思路:其实我们将一个顶点的单独拿出来,就行了,然后从两种色的开始找,不是两种色就是三种否则就是四种。因为最多四种都可以涂满。其余的dfs跑就行。

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<vector>using namespace std;int n,m,nn;struct edge{    int from;    int to;}; vector<int>G[33]; vector<edge>edges; int color[33];void addedges(int x,int y) {     edge a={x,y};     edges.push_back(a);     edge b={y,x};     edges.push_back(b);     G[x].push_back(edges.size()-2);     G[y].push_back(edges.size()-1); } int fun(int count,int x) {     for(int i=0;i<G[count].size();i++)     {         if(color[edges[G[count][i]].to]==x) return 1;     }     return 0; } int dfs(int count,int x) {   color[count]=x;     if(fun(count,x)) return 0;     if(count==n)     {         return 1;     }     for(int i=1;i<=nn;i++)     {        if(dfs(count+1,i)) return 1;     }       color[count+1]=0;     return 0; }int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        for(int i=1;i<=n;i++)            G[i].clear();        edges.clear();        for(int i=1;i<=m;i++)        {            int x,y;            scanf("%d %d",&x,&y);            addedges(x,y);        }        if(n==1) {printf("1\n");continue;}        int i;        for( i=2;i<=3;i++)        {   memset(color,0,sizeof(color));            nn=i;           if(dfs(0,0)) break;        }        if(i>3) printf("4\n");        else printf("%d\n",i);    }}