【BZOJ 3732】 Network

【題目鏈接】

          點擊打開鏈接

【算法】

           求出這個圖的最小生成樹,對於每次詢問,用倍增法求出最近公共祖先,查詢最小生成樹上兩點路徑上的最大值

           算法的正確性?

           假設x和y在最小生成樹中路徑上的最長邊爲p,那麼,根據kruskal算法的執行過程,我們發現p合併

           了x和y所在的集合

           假設有一條邊q,滿足q < p且x和y路徑上的最長邊爲q,根據kruskal算法的執行過程,我們發現這條邊必然

           不能合併x和y所在的集合

           因此,不會有比p更短的邊

【代碼】

          

#include<bits/stdc++.h>
using namespace std;
#define MAXN 15010
#define MAXM 30010
#define MAXLOG 20

struct info
{
		int x,y,d;
} edge[MAXM];
struct Edge
{
		int to,w,nxt;
} e[MAXN<<1];

int i,tot,cnt,n,m,q,x,y,d;
int fa[MAXN],dep[MAXN],anc[MAXN][MAXLOG],mx[MAXN][MAXLOG],head[MAXN];

inline void add(int x,int y,int d)
{
		tot++;
		e[tot] = (Edge){y,d,head[x]};
		head[x] = tot;
}
inline bool cmp(info a,info b) { return a.d < b.d; }
inline int get_root(int x)
{
		if (fa[x] == x) return x;
		return fa[x] = get_root(fa[x]);
}
inline void kruskal()
{
		int i,sx,sy,x,y,d;
		for (i = 1; i <= n; i++) fa[i] = i;
		sort(edge+1,edge+m+1,cmp);
		for (i = 1; i <= m; i++)
		{
				x = edge[i].x;
				y = edge[i].y;
				d = edge[i].d;
				sx = get_root(x);
				sy = get_root(y);
				if (sx != sy)
				{
						fa[sx] = sy;
						add(x,y,d);
						add(y,x,d);
				}
		}
}
inline void dfs(int u)
{
		int i,v;
		for (i = 1; i < MAXLOG; i++) 
		{
				if (dep[u] < (1 << i)) break;
				anc[u][i] = anc[anc[u][i-1]][i-1];
				mx[u][i] = max(mx[u][i-1],mx[anc[u][i-1]][i-1]);
		}
		for (i = head[u]; i; i = e[i].nxt)
		{
				v = e[i].to;
				if (anc[u][0] != v)
				{
						dep[v] = dep[u] + 1;
						anc[v][0] = u;
						mx[v][0] = e[i].w; 
						dfs(v);
				}
		}
}
inline int query(int x,int y)
{
		int i,t,ans = 0;
		if (dep[x] > dep[y]) swap(x,y);
		t = dep[y] - dep[x];
		for (i = 0; i < MAXLOG; i++)
		{
				if (t & (1 << i))
				{
						ans = max(ans,mx[y][i]);
						y = anc[y][i];
				}
		}
		if (x == y) return ans;
		for (i = MAXLOG - 1; i >= 0; i--)
		{
				if (anc[x][i] != anc[y][i])
				{
						ans = max(ans,max(mx[x][i],mx[y][i]));
						x = anc[x][i];
						y = anc[y][i];
				}
		}
		return max(ans,max(mx[x][0],mx[y][0]));
}
int main() 
{

		scanf("%d%d%d",&n,&m,&q);
		for (i = 1; i <= m; i++)
		{
				scanf("%d%d%d",&x,&y,&d);
				edge[++cnt] = (info){x,y,d};	
		}		
		kruskal();
		dfs(1);
		while (q--)
		{
				scanf("%d%d",&x,&y);
				printf("%d\n",query(x,y));
		}
		
		return 0;
	
}

           

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章