您的位置:首页 > 编程语言

编程之美 - 安排见面会问题

2016-02-01 20:07 281 查看
问题:有n个人会参加m个会议,其中一个人会参加m个会议中的若干个。怎样安排m个会议的日程使效率最高。

思路:书中的想法是将它转换为一个图的问题
例如:有5个人A,B,C,D,E 会参加5个会议 1,2,3,4,5,参加会议的情况如下。

A : { 1 - 2 - 3 } B : { 1 - 3 - 4 } C : { 2 - 3 } D : { 3 - 4 - 5 } E : { 1 - 4 - 5 }

A参加会议 1,2,3,隐含着1,2,3通过A已经关联在一起了



这样由上面 ABCDE和12345的关系可以得到一张图



由于题目要求会议的安排不能冲突,这样它就变成了图的着色问题,图中有关联的点颜色不能一样。

代码:

#include <iostream>

using namespace std;

#define MEETING 5
#define NO_COLOR 0
#define MAX_COLOR 6

// 'N'=NONE 'R'=Red 'G'=Green 'B'=Blue 'Y'=Yellow 'W'=White 'M'=MAX
char colors[MAX_COLOR+1] = {'N', 'R', 'G', 'B', 'Y', 'W', 'M'};

// A : { 1 - 2 - 3 }
// B : { 1 - 3 - 4 }
// C : { 2 - 3 }
// D : { 3 - 4 - 5 }
// E : { 1 - 4 - 5 }
int meetings[MEETING][MEETING] = {{0,1,1,1,1},
{1,0,1,0,0},
{1,1,0,1,1},
{1,0,1,0,1},
{1,0,1,1,0},};

int result[MEETING] = {NO_COLOR, NO_COLOR, NO_COLOR, NO_COLOR, NO_COLOR};

bool check(int meeting, int color)
{
int i = 0;
for (i = 0; i < MEETING; i++)
{
if ((meetings[i][meeting] != 0) && (color == result[i]))
{
return false;
}
}
return true;
}

void compute()
{
int i = 0, j = 0;

for (i = 0; i < MEETING; i++)
{
if (result[i] == NO_COLOR)
{
for (j = NO_COLOR+1; j < MAX_COLOR; j++)
{
if (!check(i, j))
{
continue;
}
else
{
result[i] = j;
break;
}
}
}
}
}

void print()
{
int i = 0;
for (i = 0; i < MEETING; i++)
{
cout << i << ":" <<colors[result[i]] << "   ";
}
cout << endl;
}

void main()
{
int i = 0;
compute();

print();
cin >> i;
}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: