POJ 1129 Channel Allocation 四色定理dfs

时间:2023-03-09 19:14:35
POJ 1129 Channel Allocation  四色定理dfs

题目: http://poj.org/problem?id=1129

开始没读懂题,看discuss的做法,都是循环枚举的,很麻烦。然后我就决定dfs,调试了半天终于0ms A了。

 #include <stdio.h>
#include <string.h>
bool graph[][], vis[][];
int n, ans; void calc()
{
int cnt = ;
for(int i = ; i < ; i++)
{
for(int j = ; j < n; j++)
{
if(vis[j][i])
{
cnt++;
break;
}
}
}
if(cnt < ans)ans = cnt;
} void dfs(int x)
{
if(x >= n)
{
calc();
return;
} for(int i = ; i < ; i++)
{
bool ok = ;
for(int j = ; j < n; j++)
{
if((graph[j][x] && vis[j][i]) || (graph[x][j] && vis[j][i]))
{
ok = ;
break;
}
}
if(ok)
{
vis[x][i] = ;
dfs(x+);
vis[x][i] = ;
}
}
} int main()
{
char s[];
while(scanf("%d", &n) != EOF && n)
{
ans = 0x3f3f3f3f;
memset(graph, , sizeof(graph));
memset(vis, , sizeof(vis));
for(int i = ; i < n; i++)
{
scanf("%s", s);
for(int j = ; s[j]; j++)
{
graph[i][s[j]-'A'] = ;
}
}
vis[][] = ;
dfs();
if(ans == )
printf("1 channel needed.\n");
else printf("%d channels needed.\n", ans);
}
return ;
}