Time Limit: 1500/1000 MS (Java/Others)
Memory Limit: 131072/131072 K (Java/Others)
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.
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set> using namespace std; struct Edge
{
int u,v,w;
};
Edge edge[+]; struct Query
{
int x,id;
};
Query qry[]; int w[+];
long long print[];
int fa[+]; void init(int n)
{
for(int i=;i<=n;i++){
fa[i]=i;
w[i]=;
}
} bool cmp1(Edge z,Edge y)
{
return z.w<y.w;
}
bool cmp2(Query z,Query y)
{
return z.x<y.x;
} int find_fa(int a)
{
if(fa[a]==a)
return a;
else{
fa[a]=find_fa(fa[a]);
w[fa[a]]+=w[a];
w[a]=;
return fa[a];
}
} void solve(int ,int ,int ); int main()
{
int test;
scanf("%d",&test);
while(test--){
int n,m,Q;
scanf("%d %d %d",&n,&m,&Q);
init(n);
for(int i=;i<=m;i++){
scanf("%d %d %d",&edge[i].u,&edge[i].v,&edge[i].w);
}
for(int i=;i<=Q;i++){
scanf("%d",&qry[i].x);
qry[i].id=i;
}
solve(n,m,Q);
}
return ;
} void solve(int n,int m,int Q)
{
sort(edge+,edge+m+,cmp1);
sort(qry+,qry+Q+,cmp2); int cnt=;
long long sum=;
for(int i=;i<=Q;i++){
while(cnt<=m&&edge[cnt].w<=qry[i].x){
int fau=find_fa(edge[cnt].u);
int fav=find_fa(edge[cnt].v);
if(fau!=fav){
sum+=w[fau]*w[fav]*;
fa[fau]=fav;
w[fav]+=w[fau];
w[fau]=;
}
cnt++;
}
print[qry[i].id]=sum;
} for(int i=;i<=Q;i++){
printf("%I64d\n",print[i]);
} return ;
}