ZOJ 1084 Channel Allocation (回溯)

来源:互联网 发布:黑桐谷歌淘宝 编辑:程序博客网 时间:2024/06/05 04:14

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1084

要解决此问题,可以先解决该问题的子问题:如何用N种颜色将Graph区分开(着色问题)。

#include <stdio.h>#include <vector>#include <algorithm>#include <iostream>#include <string.h>using namespace std;#define MAX_V 26bool IsValid(bool graph[MAX_V][MAX_V], int color[], int vIndex){for (int i = 0; i < vIndex; i++)if (graph[vIndex][i] == true) // have an edgeif (color[i] == color[vIndex]) // with the same colorreturn false;return true;}bool NColoring(bool graph[MAX_V][MAX_V], int vNum, int nColors){int color[MAX_V];memset(color, 0, sizeof(color));int vIndex = 0;while (true){if (color[vIndex] > nColors){if (vIndex == 0) // first vertexreturn false;color[vIndex] = 0;vIndex--;}else{color[vIndex]++;if (color[vIndex] <= nColors && IsValid(graph, color, vIndex)){vIndex++; // next vertexif (vIndex >= vNum)return true;}}}}int main(){int n;bool graph[MAX_V][MAX_V];char line[30];while (cin >> n && n > 0){memset(graph, false, sizeof(graph));for (int i = 0; i < n; i++){cin >> line;if (strlen(line) > 2){int vIndex = line[0] - 'A';for (int j = 2; j < strlen(line); j++)graph[vIndex][line[j] - 'A'] = true;}}for (int i = 1; ; i++)if (NColoring(graph, n, i)){if (i == 1)printf("1 channel needed.\n");elseprintf("%d channels needed.\n", i);break;}}}


原创粉丝点击