pat甲级A1034 Head of a Gang (30分) 图DFS

A1034
开始建图的时候考虑用字符串哈希,但后来看算法笔记发现map也能过就直接用map写了。

#include <bits/stdc++.h>
using namespace std;

const int N = 1e4 + 10, M = 2e8 + 10;
int h[N], e[M], ne[M], w[N], idx;
int n, k;
bool st[N];
void add(int x, int y, int w1){
	w[x] += w1;
	e[idx] = y;
	ne[idx] = h[x];
	h[x] = idx;
	idx ++;
}

map<string, int> str2i;
map<int, string> i2str;
typedef pair<string, int> PII;

void dfs(int u, int& head, int& total, int& cnt, int& sum){
	st[u] = true;
	sum += w[u];
	cnt ++;
	//printf("%d %d %s\n", cnt, w[u], i2str[u].c_str());
	if(w[u] > total){
		total = w[u];
		head = u;
	}
	for(int i = h[u]; i != -1; i = ne[i]){
		int j = e[i];
		if(!st[j]){
			dfs(j, head, total, cnt, sum);
		}
	}
}

int main(){
	memset(h, -1, sizeof h);
	int n, k;
	cin >> n >> k;
	char x[5], y[5];
	int w1, v = 0;
	for(int i = 0; i < n; i++){
		scanf("%s%s%d", x, y, &w1);
		if(!str2i[x]) {
			str2i[x] = ++ v;
			i2str[v] = x;
		}
		if(!str2i[y]) {
			str2i[y] = ++ v;
			i2str[v] = y;
		}
		add(str2i[x], str2i[y], w1), add(str2i[y], str2i[x], w1);
	}
	int num = 0;
	vector<PII> vc;
	for(int i = 1; i <= v; i++){
		int total = 0, head = 0, cnt = 0, sum = 0; 
		dfs(i, head, total, cnt, sum);
		if(cnt > 2 && sum > k*2) {
			num ++;
			vc.push_back({i2str[head], cnt});
		}
	}
	sort(vc.begin(), vc.end());
	printf("%d\n", num);
	for(int i = 0; i < num; i++){
		cout << vc[i].first << " " << vc[i].second << endl;
	}
	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值