Noip 2013 Day1 T3 货车运输 启发式并查集树

题目大意:给一个图,求最大生成树,询问生成树上两个结点路径上最小的边权,若两点不可达输出-1。

这道题是很明显的LCA问题可以倍增写(详见http://blog.csdn.net/nkwbtb/article/details/21880941),

但是我今天看了看题解,惊奇地发现了一种极其美妙的做法。

就是启发式并查集树

名字听起来非常高大上,实际上很简单,启发式并查集,就是维护每个集合的深度,在合并两个集合的时候把小的那个集合挂在大集合下。

在此题中呢,求最大生成树的同时,不把新加入的一条边作为计算答案的树,而是把两个集合的祖先加入树中,边权就是原来边的两个边权。看到这,不禁产生了疑问,树的边权和形态与求出的最大生成树都不一样,为啥能做???其实没有关系,因为新加入的边不影响 原来集合中两点的答案,合并的两个集合中的点合并后肯定要经过原来这条边,那我把祖先接起来用原来边的边权也是一样的。

但是这么做,由于使用了启发式合并,那么最后新的树高度可以证明不会超过logn(其实我也不会证),那么我们不用倍增处理这棵树,直接暴力求lca即可,不仅代码短,而且常数小!!!

代码:

3287 货车运输NKWBTB 测试通过 Accepted
100
» 464ms 3084kb C++  

#include 
#include 
#include 
#define MAXM 50001
#define MAXN 10001
using namespace std;
int fa[MAXN],rank[MAXN],ct=1,first[MAXN],dep[MAXN],val[MAXN];
int father[MAXN];
struct edge{
	int p,next,l;
	void add(int u,int v,int lth){
		p=v;
		next=first[u];
		l=lth;
	}
}line[MAXM],e[MAXM*2];
bool cmp(const edge &a,const edge &b){return a.l>b.l;}
int findset(int x){
	if(x!=fa[x])fa[x]=findset(fa[x]);
	return fa[x];
}
bool Union(int x,int y,int lth){
	int fx=findset(x);
	int fy=findset(y);
	if(fx==fy)return false;
	e[ct].add(fx,fy,lth);
	first[fx]=ct++;
	e[ct].add(fy,fx,lth);
	first[fy]=ct++;
	//把祖先加入新的树 
	if(rank[fx]>rank[fy]){
		fa[fy]=fx;
		if(rank[fy]+1>rank[fx])rank[fx]=rank[fy]+1;
	}else{
		fa[fx]=fy;
		if(rank[fx]+1>rank[fy])rank[fy]=rank[fx]+1;
	}
	//启发式合并 
	return true;
}
void dfs(int p,int dth){//遍历树处理深度 
	dep[p]=dth;
	for(int i=first[p];i;i=e[i].next){
		if(!dep[e[i].p]){
			father[e[i].p]=p;
			val[e[i].p]=e[i].l;
			dfs(e[i].p,dth+1);
		}
	}
}
int lca(int x,int y,int len){//暴力求lca 
	while(dep[x]>dep[y]){len=min(len,val[x]);x=father[x];}
	while(dep[x]
是不是比倍增好写多了!!!

你可能感兴趣的:(题解,图论)