http://acm.hdu.edu.cn/showproblem.php?pid=3938
Portal
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1921 Accepted Submission(s): 955
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
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
13
1
13
36
1
36
2
16
13
题目大意:给一个图,然后会有Q次询问,询问路径上最大权值的边的权值小于 L的路径数。
题目分析:
【1】由于Q的范围是10^4,而如果一个一个查找的话,会TLE。而观察由于每次询问并未确定对路径的起点或者终点,所以每次询问的小L值可以累加得到询问时的大L的值,也就是每次询问的查找是有重叠的,所以就可以将Q次询问的L值进行从小到大的排序,小L慢慢累加得到大L,避免了不必要的重复查询
【解题的第一步-询问存起来等待离线】
【2】由于所连接的边的权值必须不大于L,所以也要将所有边进行排序
【解题第二步-->对边进行排序,等待查询是否能够连接】
【3】而由于是求路径数,两个图【一个顶点数为A,一个为B】连成一个图之后所能增加的路径数是A*B,所以可以利用并查集判断需要连接的两个图是否已经连接,如果没有则进行连接,并且路径数增加A*B,且根节点记录的图的顶点数增加A(或者B)
【解题最关键的一步,从小到大连接边,并更新L[i]的路径数,其中利用了两个连通图连接之后路径数增加A*B的原理】
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge{
int to1;
int to2;
int lrn;
}EDGE[];
struct qury{
int id;
int x;
}qwq[];
int n,m,q;
int pre[],num[];;
int find(int x)
{ int xx=x;
while(x!=pre[x])
{
x=pre[x];
}
while(pre[xx]!=x)
{
int t=pre[xx];
pre[xx]=x;
xx=t;
}
return x;
}
bool cmp1(struct edge orz1,struct edge orz2)
{
return orz1.lrn<orz2.lrn;
}
bool cmp2(struct qury orz3,struct qury orz4)
{
return orz3.x<orz4.x;
}
int main()
{
while(scanf("%d%d%d",&n,&m,&q)==)
{
for(int i = ; i <= n ; i++)
{
pre[i]=i;
num[i]=;
}
for(int i = ; i < m ; i++)
{
scanf("%d%d%d",&EDGE[i].to1,&EDGE[i].to2,&EDGE[i].lrn);
}
sort(EDGE,EDGE+m,cmp1);
for(int i = ; i < q ; i++)
{
qwq[i].id=i;
scanf("%d",&qwq[i].x);
}
sort(qwq,qwq+q,cmp2);
int j=;
long long sum=;
long long ans[];
memset(ans,,sizeof(ans));
for(int i = ; i < q ; i++)
{
for(;j<m;j++)
{
if(EDGE[j].lrn>qwq[i].x)break;
int wqw1=find(EDGE[j].to1);
int wqw2=find(EDGE[j].to2);
if(wqw1!=wqw2)
{
pre[wqw1]=wqw2;
sum+=num[wqw1]*num[wqw2];
num[wqw2]+=num[wqw1];
}
}
ans[qwq[i].id]=sum; }
for(int i = ;i < q ; i++)
{
printf("%lld\n",ans[i]);
}
}
return ;
}