1. 程式人生 > >PAT-A 1034. Head of a Gang (dfs)

PAT-A 1034. Head of a Gang (dfs)

剛開始用並查集發現不太好處理。。用搜索就好做多了。

注意雖然路徑數最多1000,但節點數可能2000,所以陣列要開大不然段錯誤。

#include <iostream> 
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
int g[2010][2010], wei[2010], vis[2010];
int id;
int cnt, tot;
void dfs(int s) {
	for(int i = 1; i < id; i++) {
		if(g[s][i] != -1) {
			tot += g[s][i];
			g[s][i] = -1;
			if(!vis[i]) {
				cnt++;
				vis[i] = 1;
				dfs(i);
			}
		}
	}
}
map<string, int> m;
int main() {
	memset(g, -1, sizeof g);
	int n, k;
	scanf("%d %d", &n, &k);
	string a, b;
	int w;
	id = 1;
	for(int i = 0; i < n; i++) {
		cin >> a >> b >> w;
		if(!m.count(a)) m[a] = id++;
		if(!m.count(b)) m[b] = id++;  //雜湊
		g[m[a]][m[b]] = w;
		wei[m[a]] += w;
		wei[m[b]] += w;
	}
	vector<pair<string, int> > ans;
	for(int i = 1; i < id; i++) {
		if(!vis[i]) {
			vis[i] = 1;
			cnt = 1;
			tot = 0;
			dfs(i);
			int maxn = 0, maxnid = 0;
			for(int j = 1; j < id; j++) {
				if(vis[j] == 1) {
					vis[j] = -1;
					if(maxn < wei[j]) {
						maxn = wei[j];
						maxnid = j;
					}
				}
			}
			if(cnt > 2 && tot > k) {
				for(auto it = m.begin(); it != m.end(); it++) {
					if(it->second == maxnid) {
						ans.push_back(make_pair(it->first, cnt));
						break;
					}
				}
			}
		}
	}
	sort(ans.begin(), ans.end());
	cout << ans.size() << endl;
	for(int i = 0; i < ans.size(); i++) {
		cout << ans[i].first << " " << ans[i].second << endl;
	}
	return 0;
}