zoukankan      html  css  js  c++  java
  • 【树上问题1】树上距离和

    题目:给定一棵 N 个点的无向树,边有边权,求树上任意两点间的距离和,答案对 1e9+7 取模。

    题解:依题可知,这道题所求即:(Sigma_{i=1}^{n-1}Sigma_{j=i+1}^{n} dist(i,j)),枚举树上任意两点并计算距离的复杂度要达到 (O(n^2logn)),时间难以承受。
    可以换一种方式思考,由于任意两点的距离都是答案贡献的一部分,因此可以考虑每条边对答案的贡献,将这条边删去后,分成的两棵子树内的点都需要经过这条边才能到达另一棵子树,因此这条边对答案贡献为(w[i]*size[v]*(n-size[v]))

    代码如下

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn=5010;
    const int mod=1e9+7;
    
    inline int read(){
        int x=0,f=1;char ch;
        do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
        do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
        return f*x;
    }
    
    struct node{
    	int nxt,to,w;
    	node(int x=0,int y=0,int z=0):nxt(x),to(y),w(z){}
    }e[maxn<<1];
    int tot=1,head[maxn];
    inline void add_edge(int from,int to,int w){
    	e[++tot]=node(head[from],to,w),head[from]=tot;
    }
    
    int n,size[maxn];
    long long ans;
    
    void dfs(int u,int fa){
    	size[u]=1;
    	for(int i=head[u];i;i=e[i].nxt){
    		int v=e[i].to;if(v==fa)continue;
    		dfs(v,u);
    		size[u]+=size[v];
    	}
    }
    
    void read_and_parse(){
    	n=read();
    	for(int i=1;i<n;i++){
    		int from=read(),to=read(),w=read();
    		add_edge(from,to,w),add_edge(to,from,w);
    	}
    	dfs(1,0);
    }
    
    void dfs2(int u,int fa){
    	for(int i=head[u];i;i=e[i].nxt){
    		int v=e[i].to,w=e[i].w;if(v==fa)continue;
    		ans=(ans+(long long)w*size[v]*(n-size[v]))%mod;
    		dfs2(v,u);
    	}
    }
    
    void solve(){
    	dfs2(1,0);
    	printf("%lld
    ",ans);
    }
    
    int main(){
    	read_and_parse();
    	solve();
    	return 0;
    }
    
  • 相关阅读:
    WPF关于“在“System.Windows.Markup.StaticResourceHolder”上提供值时引发了异常。”问题解决办法
    未知的生成错误 因为没有预加载,所以无法解析程序集 GalaSoft.MvvmLight
    C#中的??是什么意思
    WIN10使用管理员权限运行VS2013
    路飞项目
    DRF
    Vue
    dsdffd
    python学习第45天
    python学习第44天
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/9987883.html
Copyright © 2011-2022 走看看