zoukankan      html  css  js  c++  java
  • codeforces 839C

    题目链接:https://codeforces.com/problemset/problem/839/C

    dfs

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    #include<cmath>
    #include<stack>
    #include<queue>
    using namespace std;
    typedef long long ll;
    
    const int maxn = 100010;
    
    int n;
    
    int h[maxn],cnt = 0;
    struct E{
    	int to,next;
    }e[maxn*2];
    void add(int u,int v){
    	e[++cnt].to = v;
    	e[cnt].next = h[u];
    	h[u] = cnt;
    }
    
    int deg[maxn],dep[maxn],sz[maxn];
    double p[maxn],ans;
    
    void dfs(int u,int par){
    	sz[u] = 1;
    	dep[u] = dep[par] + 1;
    	if(par==1) p[u] = p[par] * (1.0 / deg[par]);
    	else if(par!=0)p[u] = p[par] * (1.0 / (deg[par] - 1));
    	for(int i=h[u];i!=-1;i=e[i].next){
    		int v=e[i].to;
    		if(v==par) continue;
    		dfs(v,u);
    		sz[u] += sz[v];
    	}
    	if(sz[u] == 1){
    		ans += (dep[u]-1) * p[u];
    	}
    }
    
    ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }
    
    int main(){
    	memset(h,-1,sizeof(h));
    	n = read();
    	ans = 0.0;
    	int u,v;
    	for(int i=1;i<n;++i){
    		u = read(),v = read();
    		add(u,v), add(v,u);
    		++deg[u], ++deg[v];
    	}
    	
    	p[1] = 1.0;
    	dfs(1,0);
    	
    	printf("%.7f
    ",ans);
    	
    	return 0;
    }
    
  • 相关阅读:
    scala
    数据结构(01)
    基本算法(07)
    基本算法(06)
    基本算法(05)
    git pull文件时和本地文件冲突的问题
    获取两个日期之间的日期形成一个集合
    lombok的简单介绍(2)
    springboot启动报错
    逆向工程的创建
  • 原文地址:https://www.cnblogs.com/tuchen/p/13839433.html
Copyright © 2011-2022 走看看