做这题学到了什么是“离线算法”的概念。所谓“离线”,就是把所有的数据都输入之后再计算,“在线”就是边输入边计算。
用在这题中,是因为输入中的“询问部分”,有Q 个问,每个L可以有多少种不同路径。由于大的L必定会包含到小的L, 所以把所有问题都输入,再从大到小排序,再计算,可以减少很多计算量。
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
求有多少条路径使得路径上的花费小于L,这里路径上的花费是这样规定的,a、b两点之间的多条路径中的最长的边最小值!最小生成树--如果两个并查集没有连通,那么联通之后的路径条数就应该是(num[a]*num[b])........
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int father[10005],num[10005];
struct node
{
int v1,v2;
int dis;
}s[50005];
struct node1
{
int ans;
int sum;
int id;
}t[10005];
int cmp(const node a,const node b)
{
if(a.dis<b.dis)
return 1;
else
return 0;
}
int cmp1(const node1 a,const node1 b)
{
if(a.sum<b.sum)
return 1;
else
return 0;
}
int cmp2(const node1 a,const node1 b)
{
if(a.id<b.id)
return 1;
else
return 0;
}
int find(int x)
{
int root,i=x;
while(x!=father[x])
x=father[x];
root=x;
x=i;
while(x!=father[x])
{
i=father[x];
father[x]=root;
num[root]+=num[x];
num[x]=0;
x=i;
}
return root;
}
int liantong(int x,int y)
{
father[x]=y;
int k=num[y]*num[x];
num[y]+=num[x];
num[x]=0;
return k;
}
int main()
{
int n,m,q;
while(scanf("%d%d%d",&n,&m,&q)>0)
{
for(int i=0;i<=n;i++)
{
father[i]=i;
num[i]=1;
}
int maxn=0;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&s[i].v1,&s[i].v2,&s[i].dis);
maxn=s[i].dis;
}
sort(s,s+m,cmp);
for(int i=0;i<q;i++)
{
scanf("%d",&t[i].sum);
t[i].id=i;
}
sort(t,t+q,cmp1);
int j=0;
for(int i=0;i<q;i++)
{
if(i==0)
t[i].ans=0;
else
t[i].ans=t[i-1].ans;
while(j<m&&t[i].sum>=s[j].dis)
{
int tmp=s[j].v1;
int tmp1=s[j].v2;
tmp=find(tmp);
tmp1=find(tmp1);
if(tmp!=tmp1)
{
t[i].ans+=liantong(tmp,tmp1);
}
j++;
}
}
sort(t,t+q,cmp2);
for(int i=0;i<q;i++)
printf("%d\n",t[i].ans);
}
return 0;
}