例题7-6 带宽 UVa140

1.题目描述:点击打开链接

2.解题思路:原来按照紫书上的思路进行剪枝,发现总是TLE,==,也许是我还没有正确地理解书上的思路吧。无奈之下只好枚举全排列,用函数计算每个排列的k值,发现又TLE,==,最终换成在循环中计算k值,终于AC了。。。

3.代码:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<cassert>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<cmath>
#include<cstring>
#include<functional>
using namespace std;
const int maxn = 30;
const int M = 26;
int g[maxn][maxn];//邻接矩阵
int vis[maxn], b[maxn], permu[maxn],order[maxn];//vis标记该字母存在,b存储带宽,order存储排列
int k;//带宽
int cnt;
bool readin()
{
	memset(g, 0, sizeof(g));
	memset(vis, 0, sizeof(vis));
	string buf;
	cin >> buf;
	if (buf == "#")return false;
	buf += ";";
	for (int i = 0; i < buf.length(); i++)
	{
		if (isalpha(buf[i]) && buf[i + 1] == ':')
		{
			vis[buf[i] - 'A'] = 1;
			int j = i + 2;
			for (; j < buf.find_first_of(';'); j++)
			{
				g[buf[i] - 'A'][buf[j] - 'A'] = g[buf[j] - 'A'][buf[i] - 'A'] = 1;
				if (!vis[buf[j] - 'A'])vis[buf[j] - 'A'] = 1;
			}
			buf[j] = ' ';
			i = j;
		}
	}
	return true;
}

void dfs()
{
	do
	{
		int max_band = 0;
		for (int i = 0; i < cnt; i++)
		for (int j = i + 1; j < cnt; j++)
		if (g[permu[i]][permu[j]])
		{
			int len = j - i;
			if (len>max_band)
				max_band = len;
		}
		if (max_band < k)
		{
			k = max_band;
			for (int i = 0; i < cnt; i++)
				order[i] = permu[i];
		}
		else continue;
	} while (next_permutation(permu, permu + cnt));
}

int main()
{
	while (readin())
	{
		cnt = 0;
		memset(permu, 0, sizeof(permu));
		memset(order, 0, sizeof(order));
		for (int i = 0; i < M;i++)
		if (vis[i])permu[cnt++] = i;
		k = 100;
		dfs();
		for (int i = 0; i < cnt; i++)
			printf("%c ", 'A' + order[i]);
		printf("-> %d\n", k);
	}
	return 0;
}

你可能感兴趣的:(uva)