补一个简单的数据结构——带权并查集

讲解

http://www.cnblogs.com/wally/archive/2013/06/10/3130527.html

Code

int fa[N];
LL dist[N];

void init() {
  for (int i=1;i<=n;++i) {
        fa[i]=i;
  }
  RST(dist);
}
int find(int x){
  int y = x;
  if (fa[x] == x) return x;
  y = find(fa[x]);
  dist[x] += dist[fa[x]];
  return fa[x] = y;
}
bool unionset(int x,int y , LL w){       // dist[y] - dist[x] = w
   int rx = find(x) , ry = find(y);
   if (rx == ry && dist[y] != dist[x] + w) return false;
   if (rx == ry) return true;
   fa[ry] = rx;
   dist[ry] = dist[x] - dist[y] + w;
   return true;
}


你可能感兴趣的:(补一个简单的数据结构——带权并查集)