图的着色优化问题

来源:互联网 发布:oracle数据库全库备份 编辑:程序博客网 时间:2024/06/05 19:23
在GSM通信系统中,为了避免相邻基站之间的干扰要求相邻的基站之间不能采用相同的频率来进行通信。 由于频率资源有限,因此就要求基站所占用的频率资源越少越好。

输入要求:

   输入包含某地区的基站之间的相邻情况。输入的第一行为一个整数n,表示有多少个邻接信息。后面的n行每一行包含一个邻接关系,每一行的形式如下:

    A:BCDH

其中A 表示某给基站的名称,:后的每一个字母都表示一个基站的名称,表示与A相邻的基站,基站数量在1~26之间,分别对应1~26个字母。如果某个基站没有相邻的基站,则形式如下:

B:

表示没有与基站B相邻的基站。

输出要求:

输出只有一行,一个整数,也就是需要的最少的频率数。

样例输入:

4
A:BCD
B:ACD
C:ABD
D:ABC



样例输出:

4


很明显,此题可转化为图的着色优化问题,只是颜色限制数目没有给出。算法同理,使用回溯法,以每个基站的配色作为每层搜索的对象,以判断邻接表中相邻基站的配色情况作为剪枝函数,只有当新的颜色出现之后,color_num才会自加。对于m色着色问题,大家可以参考这篇文章

http://blog.csdn.net/liufeng_king/article/details/8781554

具体实例分析如下:

输入:

4

A:BCD

B:ACD

C:ABD

D:ABC

此时,n=4,邻接表转换为

0111

1011

1101

1110

首先对于基站A配色,配色为1,使用color_ok函数查找发现配色无冲突,继续配色B,配色为1,配色冲突,配色为2,无冲突。3、4同理。于是最小的频率数为4。此题的解空间如下所示。

因此,求解代码如下:

#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <algorithm>#include <sstream>#include <iostream>#include <cstdio>#include <cmath>#include <cstdlib>#include <cstring>#include <string>#include <ctime>#define fur(i,a,b) for(int i=(a);i<=(b);i++)#define furr(i,a,b) for(int i=(a);i>=(b);i--)#define cl(a) memset((a),0,sizeof(a))using namespace std;typedef long long ll;typedef unsigned long long ull;typedef pair <int, int> pii;const int inf = 0x3f3f3f3f;const double eps = 1e-8;const int mod =  1000000007;const double pi = acos(-1.0);const int N = 1010;int n;int neighbor[N][N];int color[N];int color_num = 0;void Backtrack(int t);char record[N];bool color_ok(int i, int num);int main(){while (scanf("%d\n", &n) !=EOF){for (int i = 0; i < n; i++){scanf("%s",record);for (int j = 2; record[j] != 0; j++){neighbor[i][record[j] - 'A'] = 1;}}Backtrack(0);}return 0;}bool color_ok(int i, int num){for (int j = 0; j < n; j++){if (neighbor[i][j]==1)if (color[j] == num)return false;}return true;}void Backtrack(int t){if (t>=n){printf("%d\n", color_num);return;}else{int i = 1;for (; i <= t; i++) {color[t] = i;if (color_ok(t, i)){Backtrack(t + 1);return;}}color[t] = i;if (color_ok(t,i)){color_num++;Backtrack(t + 1);return;}}}



0 0