码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-12-24 21:36:59      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:acm   subject   ever   max   ++   示例   between   ret   using   

题目描述

 

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;
}

  

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

标签:acm   subject   ever   max   ++   示例   between   ret   using   

原文地址:http://www.cnblogs.com/zufezzt/p/8099049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!