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;
    }
    

      

  • 相关阅读:
    oracle11g 新特性
    RMAN 报:ORA-19504 ORA-27038
    ORACLE-用户常用数据字典的查询使用方法
    oracle
    收缩 表空间
    oracle 配置 oem
    索引大小及占表的空间
    Oracle 11g Windows 迁移至 Linux
    Python:列表生成式
    Python:字符串处理函数
  • 原文地址:https://www.cnblogs.com/DriverLao/p/8401449.html
Copyright © 2011-2022 走看看