POJ 3140 Contestants Division

题目描述

 

总结

1. DFS 使用 dfs(u, v) 框架可以省去 visited[]; 还可以添加一个辅助的 dummy 头结点

2. 需要 long long 类型才可以

3. 题目本身比较简单, DFS 后序遍历, 树形 DP 的最简单题型

 

代码 数据类型有误

/*
 * source.cpp
 *
 *  Created on: 2014-4-5
 *      Author: vincent
 */
#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <map>
#include <vector>
#include <algorithm>
#include <set>
#include <deque>
#include <queue>
using namespace std;

const int NUM = 100010;
int val[NUM];
vector<int> graph[NUM];
map<int, int> mymap;

int globalMinCut;
int totalWeight;
int dfs(int u, int v) {
	int sumWeight = 0;
	for(size_t i = 0; i < graph[v].size(); i ++) {
		int index = graph[v][i];
		if(index == u) continue;
		int partyWeight = dfs(v, index);
		globalMinCut = min(globalMinCut, abs(partyWeight-totalWeight));
		sumWeight += partyWeight;
	}
	sumWeight += val[v];
	return sumWeight;
}

int main() {
	freopen("C:\\Users\\vincent\\Dropbox\\workplacce\\joj\\test.txt", "r", stdin);

	int n, m;
	int cases = 1;
	while(scanf("%d%d", &n, &m) != EOF && n != 0 && m != 0) {
		mymap.clear();
		for(int i = 0; i <= n; i ++)
			graph[i].clear();
		totalWeight = 0;

		for(int i = 1; i <= n; i ++) {
			scanf("%d", &val[i]);
			totalWeight += val[i];
		}

		int index = 1;
		for(int i = 0; i < m; i ++) {
			int a, b;
			scanf("%d%d", &a, &b);
			if(!mymap.count(a)){
				mymap[a] = index ++;
			}
			if(!mymap.count(b)) {
				mymap[b] = index ++;
			}

			int indexa = mymap[a];
			int indexb = mymap[b];
			graph[indexa].push_back(indexb);
			graph[indexb].push_back(indexa);
		}
		globalMinCut = 0x3f3f3f3f;
		int st = mymap.begin()->second;

		graph[index].push_back(st);
		dfs(index, st);
		printf("Case %d: %d\n", cases++, globalMinCut);
	}
	return 0;
}

  

posted @ 2014-04-05 10:49  周卓  阅读(158)  评论(0编辑  收藏  举报