湖南大学ACM程序设计新生杯大赛(同步赛)B - Build

题目描述

 

In country  A, some roads are to be built to connect the cities。However, due to limited funds, only some roads can be built.That is to say,if the limit is 100$, only roads whose cost are no more than 100$ can be built.

Now give you n cities, m roads and the cost  of each road wi (i=1..m). There are q queries, for each query there is a number k, represent the limit, you need to output the maximum number of pairs of cities that can reach each other. 

 

输入描述:

The first line consist of two integers, n,m, n the number of cities and m the number of roads. The next m lines , each line has three integers a,b,w, represent that you can bulid a road between city a and city b with cost w.
The next line an integer q, the number of querries. The next q lines each an integer k ,the limit of the fund.
n<10000, m < 10000, k < 10000, q<10000;

输出描述:

For each querry ,you should output the anwser.
示例1

输入

3 2
1 2 1
2 3 2
1
2

输出

3

题解

并查集。

按边排序做并查集,处理好每一条边加进去之后的答案。每次询问,找到符合要求的最后一条边权加入后的答案。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
 
const int maxn = 500000 + 10;
int f[maxn];
int c[maxn];
long long A;
int n, m;
struct Edge {
  int a, b, c;
}e[maxn];
 
long long ans[maxn];
 
bool cmp(Edge &a , Edge &b) {
  return a.c < b.c;
}
 
int Find(int x) {
  if(x != f[x]) f[x] = Find(f[x]);
  return f[x];
}
 
int main() {
  while(~scanf("%d%d", &n, &m)) {
    for(int i = 1; i <= n; i ++) {
      f[i] = i;
      c[i] = 1;
    }
    A = 0;
    for(int i = 1; i <= m; i ++) {
      scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].c);
      ans[i] = 0;
    }
    sort(e + 1, e + 1 + m, cmp);
    for(int i = 1; i <= m; i ++) {
      int fx = Find(e[i].a);
      int fy = Find(e[i].b);
      if(fx == fy) {
        ans[i] = A;
        continue;
      }
      A = A + c[fx] * c[fy];
      f[fx] = fy;
      c[fy] += c[fx];
      ans[i] = A;
    }
 
    int Q;
    scanf("%d", &Q);
    while(Q --) {
      int x;
      scanf("%d", &x);
      int L = 1, R = m, p = 0;
      while(L <= R) {
        int mid = (L + R) / 2;
        if(e[mid].c <= x) p = mid, L = mid + 1;
        else R = mid - 1;
      }
      printf("%lld\n", ans[p]);
    }
 
  }
  return 0;
}

  

转载于:https://www.cnblogs.com/zufezzt/p/8099049.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值