HDU3938 Portal(最小生成树 + 计数)

Problem Description

ZLGG found a magic theory that the bigger banana the bigger banana peel .This important theory can help him make a portal in our universal. Unfortunately, making a pair of portals will cost min{T} energies. T in a path between point V and point U is the length of the longest edge in the path. There may be lots of paths between two points. Now ZLGG owned L energies and he want to know how many kind of path he could make.

Input

There are multiple test cases. The first line of input contains three integer N, M and Q (1 < N ≤ 10,000, 0 < M ≤ 50,000, 0 < Q ≤ 10,000). N is the number of points, M is the number of edges and Q is the number of queries. Each of the next M lines contains three integers a, b, and c (1 ≤ a, b ≤ N, 0 ≤ c ≤ 10^8) describing an edge connecting the point a and b with cost c. Each of the following Q lines contain a single integer L (0 ≤ L ≤ 10^8).

Output

Output the answer to each query on a separate line.

Sample Input

10 10 10
7 2 1
6 8 3
4 5 8
5 8 2
2 8 9
6 4 5
2 1 5
8 10 5
7 3 7
7 8 8
10
6
1
5
9
1
8
2
7
6

Sample Output

36
13
1
13
36
1
36
2
16
13

中文题意

给你一个图,有q个询问,每次询问给一个值L,每次询问问的是有多少个点对,这些点对满足起点到终点所有路径中每条路径最长边中取最小值T(有点拗口哈,就是起点到终点所有路径的最长边取min)小于L。

分析

这道题和NOIP2013货车运输很相似。其实只要发现,所有路径的最长边的最小值一定在最小生成树上就行了!为什么呢?我们考虑最长边的最小值对应的那条边,它连接的是两个点集对吧,把它割掉,我们来看看这条边有什么特点。不难发现,这条边是连接两个集合的最小边,(如果不是最小,明显有其他路径来取代原路径),而这正是最小生成树上的边的特点啊!因此这条边一定在最小生成树上,我们只需枚举最小生成树上的边即可。
因此我们按询问和边都从小到大排个序,枚举边,如果超过当前询问,就把当前计数sum作为当前询问的答案。每次合并两个集合的时候,sum+=cnt[a]cnt[b]sum += cnt[a] * cnt[b]sum+=cnt[a]∗cnt[b]就可以了。
在补充一下:为什么不用考虑不在最小生成树上的边呢?因为不在最小生成树上的边加上去就会形成一个环,而不加这条边的时候这个集合已经连通了,加了这条边,它明显大于环上其他的边,而环上任意两点满足题意的路径不可能覆盖了这条边的,因此不可能成为我们要的T。

代码如下:

#include <bits/stdc++.h>
#define LL long long
#define N 10050
using namespace std;
struct node{
	int a, b, c, i;
	bool operator < (const node & A) const{
		return c < A.c;
	}
}d[N * 5], q[N];
int f[N], p[N], sum, ans[N], cnt[N];
int find(int x){
	return x == f[x]? x: f[x] = find(f[x]);
}
int main(){
	int i, j, n, m, t, a, b, c;
	while(scanf("%d%d%d", &n, &m, &t) != EOF){
		for(i = 1; i <= n; i++) f[i] = i;
		for(i = 1; i <= m; i++) scanf("%d%d%d", &d[i].a, &d[i].b, &d[i].c);
		sort(d + 1, d + i);
		for(i = 1; i <= t; i++) scanf("%d", &q[i].c), q[i].i = i;
		sort(q + 1, q + i);
		for(i = 1; i <= t; i++) p[q[i].i] = i;
		for(i = 1; i <= n; i++) cnt[i] = 1;
		j = 1; sum = 0;
		for(i = 1; i <= m; i++){
			c = d[i].c;
			while(c > q[j].c && j <= t){
				ans[j++] = sum;
			}
			a = find(d[i].a); b = find(d[i].b);
			if(a != b){
				f[b] = a;
				sum += cnt[a] * cnt[b];
				cnt[a] += cnt[b];
			}
		}
		while(j <= t) ans[j++] = sum;
		for(i = 1; i <= t; i++) printf("%d\n", ans[p[i]]);
	}
	return 0;
}
上一篇:什么是Portal认证


下一篇:java – jetspeed 2和pluto有什么区别?