poj 1986 Distance Queries (lca,在线做法dfs+rmq)

题目链接 题意:求树上两点的最短距离? 思路: dis[i]表示点i到根节点的距离,那么任意两点u,v的最短距离d = dis[u]+dis[v]-2*dis[LCA(u,v)]. 只需要求出rmq+dfs的在线方法求出lca(u,v)即可。

/* ***********************************************
Author :111qqz
Created Time :2016年05月20日 星期五 15时36分47秒
File Name :code/poj/1986.cpp
************************************************ */

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair

using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
const int N=4E4+7;
int n,m;
vector < pi > edge[N];
int q;
int in[N];
int E[2*N],R[2*N],dis[N],depth[2*N];
int p;
int dp[2*N][20];
void dfs( int u,int dep,int d,int pre)
{

  //  cout<<"u:"<<u<<" dep:"<<dep<<" d:"<<d<<endl;
    p++;
    E[p] = u;
    depth[p] = dep;
    R[u] = p ;
    dis[u] = d;


    int siz = edge[u].size();
    for ( int i = 0 ; i < siz ; i++)
    {
	int v = edge[u][i].fst;
	if (v==pre) continue;
	dfs(v,dep+1,d+edge[u][i].sec,u);

	p++;
	E[p] = u;
	depth[p] = dep;
    }
}



int _min( int l,int r)
{
    if (depth[l]<depth[r]) return l;
    return r;
}
void rmq_init()
{
    for ( int i = 1 ; i <= 2*n+2 ; i++) dp[i][0] = i;

    for ( int j = 1 ; (1<<j) <= 2*n+2 ; j++)
	for ( int i = 1 ; i + (1<<j)-1 <= 2*n+2 ; i++)
	dp[i][j] = _min(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
}

int rmq_min( int l,int r)
{
if (l>r) swap(l,r);
int k = 0 ;
while (1<<(k+1)<=r-l+1) k++;
return _min(dp[l][k],dp[r-(1<<k)+1][k]);
}
int main()
{
    #ifndef  ONLINE_JUDGE 
	freopen("code/in.txt","r",stdin);
  #endif
	
	ms(in,0);
	scanf("%d %d",&n,&m);
	for ( int i = 1 ; i <= n ; i++) edge[i].clear();
	for ( int i = 1 ; i <= m ; i++)
	{
	    int u,v,w;
	    char dir[5];
	    scanf("%d%d%d%s",&u,&v,&w,dir);
	    edge[u].push_back(make_pair(v,w));
	    edge[v].push_back(make_pair(u,w));
	}

	
	p = 0 ;
	dfs(1,0,0,-1);
	rmq_init();
	
	scanf("%d",&q);
	while (q--)
	{
	    int u,v;
	    scanf("%d%d",&u,&v);
	   // cout<<"u:"<<u<<" v:"<<v<<endl;
	    int LCA = E[rmq_min(R[u],R[v])];
	//    cout<<"LCA:"<<LCA<<endl;
	    int ans;
	    ans = dis[u]+dis[v]-2*dis[LCA];
	    printf("%d\n",ans);
	}
  #ifndef ONLINE_JUDGE  
  fclose(stdin);
  #endif
    return 0;
}