zoukankan      html  css  js  c++  java
  • BZOJ 1602 USACO 2008 Oct. 牧场行走

    【题解】

      要求出树上两点间的距离,树上的边有边权,本来应该是个LCA。

      看他数据小,Xjb水过去了。。。其实也算是LCA吧,一个O(n)的LCA。。。

    #include<cstdio>
    #include<algorithm>
    #define N (1010)
    #define rg register
    #define LL long long
    using namespace std;
    int n,m,root,cnt,tot,dep[N],in[N],out[N],fa[N],last[N],a[N][N];
    LL ans=0;
    struct edge{
    	int to,pre,dis;	
    }e[N<<1];
    inline int read(){
    	int k=0,f=1; char c=getchar();
    	while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
    	while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar();
    	return k*f;
    }
    inline void add(int x,int y,int z){e[++tot]=(edge){y,last[x],z}; last[x]=tot;}
    void dfs(int x,int father){
    	in[x]=++cnt; dep[x]=dep[father]+1;
    	for(rg int i=last[x],to;i;i=e[i].pre) if((to=e[i].to)!=father) dfs(to,fa[to]=x);
    	out[x]=++cnt;
    }
    inline bool IN(int x,int y){
    	if(in[y]<=in[x]&&out[x]<=out[y]) return 1;
    	return 0;
    }
    int main(){
    	n=read(); m=read();
    	for(rg int i=1,u,v,dis;i<n;i++){
    		u=read(),v=read(),dis=read();
    		add(u,v,dis),add(v,u,dis);
    		a[u][v]=a[v][u]=dis;
    	}
    	dfs(1,0);
    	//for(int i=1;i<=n;i++) printf("%d %d
    ",in[i],out[i]);
    	for(rg int i=1,x,y;i<=m;i++){
    		x=read(); y=read(); ans=0;
    		if(dep[x]<dep[y]) swap(x,y);
    		while(!IN(y,x)) ans+=a[x][fa[x]],x=fa[x];
    		while(x!=y) ans+=a[y][fa[y]],y=fa[y];
    		printf("%lld
    ",ans);
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    二分法
    php冒泡排序
    php位运算
    php学习函数如何执行的
    php学习 打星星
    小程序的学习备注
    一个IP与多个域名绑定
    apache、mysql、php核心、phpmyadmin的安装及相互关联
    php虚拟主机配置( 输入网址 对应 ip地址)
    ORA-01084: OCI 调用中的参数无效
  • 原文地址:https://www.cnblogs.com/DriverLao/p/8401449.html
Copyright © 2011-2022 走看看