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
带权并查集的题,主要是题意比较费解,搞了半天才弄明白
首先不能一次一次的查找,1e8次查找肯定会爆掉的,所有数据输入完之后,查一次就好
把输入的边按照权值升序排列,要查询的花费也升序排列
因为花费等于一条路的最长边的值,所以按照边的权值升序排列,依次加入图中,即可求得不大于此花费的路径数目
要进行并查集运算的两点可以看做两幅图,两幅图合并所增加的路径数目为两图的节点数a*b
所以用一个数组存节点数,再用一个变量存不大于当前花费的路径数目(累加即可)
另:成环的时候不增加路径,很容易想到,边是递增序,新加入的肯定大于之前的,而题目又要求最长边最小,所以不会经过这条边
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<functional>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define CL(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 5e4+10;
const int MOD = 1e9+7;
int edge[maxn], pre[maxn], ans[maxn];
struct Graph{
int from, to, val;
friend bool operator < (const Graph &a, const Graph &b){
return a.val < b.val;
}
}g[maxn];
struct Quiry{
int L, id;
friend bool operator < (const Quiry &a, const Quiry &b){
return a.L < b.L;
}
}q[maxn];
void init(int n){
for(int i = 1; i <= n; i++){
edge[i] = 1;
pre[i] = i;
}
}
int find(int x){
return x == pre[x] ? x : pre[x] = find(pre[x]);
}
int merge(int x, int y){
int fx = find(x), fy = find(y);
if(fx == fy) return 0;//成环不增加路径
int cnt = edge[fx]*edge[fy];
edge[fx] += edge[fy];
pre[fy] = fx;
return cnt;
}
int main(){
int n, m, Q, kcase = 1;
while(scanf("%d%d%d", &n, &m, &Q) == 3){
for(int i = 0; i < m; i++) scanf("%d%d%d", &g[i].from, &g[i].to, &g[i].val);
for(int i = 0; i < Q; i++){
scanf("%d", &q[i].L);
q[i].id = i;
}
init(n);
sort(g, g+m); sort(q, q+Q);
int sum, t;
sum = t = 0;
for(int i = 0; i < Q; i++){
while(t < m && g[t].val <= q[i].L){
sum += merge(g[t].from, g[t].to);//累加合并两点(两图)增加的路径数
t++;
}
ans[q[i].id] = sum;//保留原有的顺序
}
for(int i = 0; i < Q; i++) printf("%d\n", ans[i]);
}
return 0;
}