Travel
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 2404 Accepted Submission(s): 842
For each test case, the first line consists of three integers n,m and q where n≤20000,m≤100000,q≤5000. The Undirected Kingdom has n cities and mbidirectional roads, and there are q queries.
Each of the following m lines consists of three integers a,b and d where a,b∈{1,...,n} and d≤100000. It takes Jack d minutes to travel from city a to city b and vice versa.
Then q lines follow. Each of them is a query consisting of an integer x where x is the time limit before Jack goes berserk.
Note that (a,b) and (b,a) are counted as different pairs and a and b must be different cities.
1
5 5 3
2 3 6334
1 5 15724
3 5 5705
4 3 12382
1 3 21726
6000
10000
13000
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#define Max 20000+5
using namespace std;
struct edge
{
int s,e,val;
}a[+];
struct ques
{
int d,id,res;
}p[];
int per[Max],num[Max];
int n,m,q;
bool cmp(ques a,ques b)
{
return a.d<=b.d;
}
bool cmp1(ques a,ques b)
{
return a.id<b.id;
}
void init()
{
for(int i=;i<=n;i++)
{
per[i]=i;
num[i]=;
}
for(int i=;i<=q;i++)
p[i].res=;
}
int find(int x)
{
if(x==per[x])
return x;
return per[x]=find(per[x]);
}
int unite(int a,int b)
{
a=find(a);
b=find(b);
if(a<b) //a最大
swap(a,b);
per[a]=b; //根节点下标最小,记录树的节点个数
num[b]+=num[a];
return ;
}
bool cmp2(edge a,edge b)
{
return a.val<b.val;
}
int main()
{
int T;
int i,j;
freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&n,&m,&q);
init();
for(i=;i<m;i++)
scanf("%d%d%d",&a[i].s,&a[i].e,&a[i].val);
for(i=;i<q;i++)
{
scanf("%d",&p[i].d);
p[i].id=i;
}
sort(a,a+m,cmp2);
sort(p,p+q,cmp);
j=;
int t1,t2,ans=;
for(i=;i<q;i++)
{
while(j<m&&a[j].val<=p[i].d)
{
t1=find(a[j].s);
t2=find(a[j].e);
j++;
if(t1!=t2)
{
ans+=*num[t1]*num[t2];
unite(t1,t2);
}
}
p[i].res=ans;
}
sort(p,p+q,cmp1);
for(i=;i<q;i++)
printf("%d\n",p[i].res);
}
}