UVA140 带宽 Bandwidth

知识点:枚举

这个题看了一下就是深搜实现的排列枚举,刘汝佳说了可以剪枝,但是暂时还没有那么写,因为数据很小,所以不剪枝也能过了,过段时间再开始练习剪枝,这个题模拟的成分也比较高,洛谷上面提交的一直在waiting,但是上vjudge提交就过了可以测评

#include 

using namespace std;

const int N = 105;

int n, tot, ver[N], nxt[N], head[N];
int a[N], vis[N], order[N], ans, b[N];

void add(int x, int y) {
	ver[++tot] = y;
	nxt[tot] = head[x]; head[x] = tot;
}

void dfs(int k) {
	if (k == n + 1) {
		int pos[30];
		for (int i = 1; i <= n; i++) pos[order[i]] = i;
		int w = 0;
		for (int i = 0; i < n; i++) {
			int cur = 0;
			for (int j = head[a[i]]; j; j = nxt[j]) {
				int y = ver[j];
				cur = max(cur, abs(pos[a[i]] - pos[y]));
			}
			w = max(w, cur);
		}
		if (w < ans) {
			ans = w;
			for (int i = 1; i <= n; i++) b[i] = order[i];
		}
		return;
	}
	for (int i = 0; i < n; i++) {
		if (vis[a[i]]) continue;
		vis[a[i]] = 1;
		order[k] = a[i];
		dfs(k + 1);
		vis[a[i]] = 0;
	}
}

int main() {
	string s;
	while (cin >> s && s != "#") {
		n = tot = 0;
		memset(head, 0, sizeof(head));
		memset(vis, 0, sizeof(vis));
		ans = 1e9;
		for (int i = 0; i < (int) s.size(); i++) {
			if (s[i] == ';') s[i] = ' ';
		}
		stringstream ss(s);
		string tmp;
		int Hash[N] = {};
		int mp[30][30] = {};
		while (ss >> tmp) {
			if (!Hash[tmp[0] - 'A']) {
				Hash[tmp[0] - 'A'] = 1;
				a[n++] = tmp[0] - 'A';
			}
			for (int i = 2; i < (int) tmp.size(); i++) {
				int x1 = tmp[0] - 'A';
				int x2 = tmp[i] - 'A';
				if (mp[x1][x2] || mp[x2][x1]) continue;
				mp[x1][x2] = mp[x2][x1] = 1;
				add(x1, x2); add(x2, x1);
				if (!Hash[x2]) {
					Hash[x2] = 1;
					a[n++] = x2;
				}
			}
		}
		sort(a, a + n);
		dfs(1);
		for (int i = 1; i <= n; i++) {
			printf("%c ", b[i] + 'A');
		}
		cout << "-> " << ans << '\n';
	}
	return 0;
}

你可能感兴趣的:(加入题解目录题解,算法,深度优先,哈希算法)