POJ 1129 Channel Allocation (DFS)

来源:互联网 发布:阿里小号登录用淘宝 编辑:程序博客网 时间:2024/05/02 12:19

题目链接

题意
      有n个中继器,每一个中继器可能有相邻的几个中继器,为避免干扰,相邻的中继器的信号不能在同一个频道上传输。
      题目输入n个中继器的邻接表,求出这组中继器最少需要使用的频道数,详细信息看题目。

数据范围的一些限定
1 < n <= 26

思路
      问题类似于染色问题,对平面上n个格子进行染色,相邻格子不能具有相同的颜色,输入给出每个格子有哪一些相邻的格子,求最少需要使用的颜色数。将其转化为图论模型,一个格子是一个点,相邻格子用边连接,则这n个格子最多可以构成n个连通分量,属于不同连通分量的点之间不产生影响,那么可以求出每一个连通分量所需的最少颜色数,然后找出其最大值即为答案。
      怎么求出每一个连通分量所需的最少颜色数?用DFS对每一个连通分量模拟染色过程。
(1)用某一个颜色对某个未染色的点进行染色(颜色有编号,从编号小的颜色开始试)
(2)判断上一个被染色点的颜色是否和当前被染色点的颜色相同,如果相同,则当前被染色点需要换一种颜色(如果当前用过的所有颜色都产生冲突,则增加一种颜色,用该颜色对该点进行染色),若上一个被染色点的颜色和当前被染色点的颜色不同,则跳往第三步
(3)判断是否存在一个已染色相邻结点与自己的颜色相同,若存在,则当前被染色点要换一种颜色(如果当前用过的所有颜色都产生冲突,则增加一种颜色,用该颜色对该点进行染色),若不存在,则当前结点染色完毕,接下来对当前结点的所有未染色相邻结点进行染色。
      重复上面的三步,直到所有点都染完色了为止。

      以下是代码,各种多余头文件宏定义什么的请无视,在vimrc里写好了,懒得删掉了,可以视为我在装13。如果在其中发现有错误,请指出,发表此文部分原因是希望有人能够指出我可能存在的错误。如果有人有更好的解法,请不吝赐教。

/* * Author:  Fiend * Created Time:  2013/4/16 17:25:06 * File Name: test.cpp */#include <iostream>#include <cstdio>#include <cstddef>#include <cmath>#include <algorithm>#include <string>#include <cstring>#include <vector>#include <bitset>#include <stack>#include <queue>#include <set>#include <map>#include <cctype>#define ST size_type#define PB push_back#define LL long long#define MAXN 30using std::cin;using std::cout;using std::endl;using std::string;using std::bitset;using std::vector;using std::pair;using std::swap;using std::sort;using std::max;using std::min;const int inf = 0x3fffffff;typedef pair<int, int> pii;typedef vector<int> vi;typedef vector<int>::iterator vit;vi graph[MAXN];int color[MAXN];int getIndex (char ch) {return ch - 'A' + 1;}//index表示当前被染色点的下标,c表示上一个被染色点的颜色void dfs (int index, int c) {bool done = false;vi::const_iterator i;//对当前点染色并检查冲突color[index] = 1;//当前结点染1号颜色for (color[index] = 1; done == false; ++color[index]) {//当前结点与上一个被染色点颜色相同if (color[index] == c)continue;//判断是否存在一个已染色相邻结点与自己的颜色相同i = graph[index].begin ();while (i != graph[index].end ()) {if (color[*i] != 0 && color[index] == color[*i])break;++i;}if (i == graph[index].end ()) {done = true;break;}}//对当前结点的所有未染色相邻结点进行染色for (i = graph[index].begin (); i != graph[index].end (); ++i)if (color[*i] == 0)dfs (*i, color[index]);}int main () {int n, next, ans;string ad;while (cin >> n, n != 0) {//建立邻接表for (int i = 1; i <= n; ++i)graph[i].clear ();for (int i = 1; i <= n; ++i) {cin >> ad;for (string::ST j = 2; j != ad.size(); ++j) {next = getIndex (ad[j]);graph[i].PB (next);}}//对每一个连通分量染色memset (color, 0, sizeof (color));for (int i = 1; i <= n; ++i)if (color[i] == 0)dfs (i, 0);//找到所需的颜色数并输出ans = 1;for (int i = 1; i <= n; ++i)if (color[i] > ans)ans = color[i];cout << ans << " channel";if (ans != 1)cout << "s";cout << " needed." << endl;}return 0;}