HDU - 5441 Travel 并查集+离线查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiang_6/article/details/81773172

题意:

略;

思路:

首先对于能连通的点之间可以相互到达,

对于给定的某个限定,我们可以把可行的路径找出来,然后计算每个连通块能相互到达的点对,然后加起来

但是这样复杂度太大,所以我们把q个查询离线出来,从小到达排序,然后用并查集维护每个连通块,以及他们的大小,可以得到答案;

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <cmath>
using namespace std;
typedef long long ll;
const int maxn = 20000+10;
const int maxd = 1e5 + 7;
int n,m,q;
int f[maxn];
int cnt[maxn];

void init() {
  for(int i = 0; i < maxn; i++) {
    f[i] = i;
    cnt[i] = 1;
  }
}
int find(int x) {
  if(f[x]==x)
    return x;
  else
    return f[x] = find(f[x]);
}
void merge(int x,int y) {
  int t1 = find(x);
  int t2 = find(y);
  if(t1!=t2)
    f[t2] = t1;
}
bool same(int x,int y) {
  return find(x)==find(y);
}
struct node {
  int a, b, d;
} a[maxd];
bool cmp(node a, node b) {
  return (a.d < b.d);
}
struct node1 {
  int li, id;
} b[5010];
bool cmp1(node1 a, node1 b) {
  return (a.li < b.li);
}

int ans[maxn];
set<int> st;

void solve() {
  int j = 1;
  for(int i = 1; i <= q; ++i) {
    for(; j <= m; ++j) {
      if(a[j].d > b[i].li) break;
      int u = a[j].a, v = a[j].b, d = a[j].d;
      if(same(u,v)) continue;

      int u_ = find(u), v_ = find(v);
      if(st.count(u_)) st.erase(st.find(u_));
      if(st.count(v_)) st.erase(st.find(v_));
      f[v_] = u_;
      cnt[u_] += cnt[v_];
      st.insert(u_);
    }
    int anss = 0;
    for(auto i : st) {
      anss += (cnt[i]*(cnt[i]-1));
    }
    ans[b[i].id] = anss;
  }
  for(int i = 1; i <= q; ++i) {
    printf("%d%c", ans[i], '\n');
  }
}

int main() {
  int T;
  scanf("%d",&T);
  while(T--) {
    init();
    st.clear();
    scanf("%d%d%d",&n,&m,&q);
    for(int i = 1; i <= m; ++i) {
      scanf("%d%d%d", &a[i].a, &a[i].b, &a[i].d);
    }
    sort(a+1,a+1+m, cmp);
    for(int i = 1; i <= q; ++i) {
      scanf("%d", &b[i].li);
      b[i].id = i;
    }
    sort(b+1,b+1+q,cmp1);
    solve();
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/xiang_6/article/details/81773172