description
stringlengths
35
9.39k
solution
stringlengths
7
465k
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
n = int(input("")) Map = {s:set() for s in range(1, n + 1)} # def process(x, y): # Map[x].append(y) # Map[y].append(x) for i in range(n-1): x, y = map(int, input().split()) # x=int(input("xxxxxxxxxx")) # y=int(input("yyyyyyyyyy")) Map[x].add(y) Map[y].add(x) sum = 0 cities = set() a = [[0, 1, 1]] while a != []: # print("@@@@@@@@@@@@@",a) near_cities = 0 number = a[-1][0] city = a[-1][1] pro = a[-1][2] cities.add(city) # for i in Map[city]: # if i not in cities: near_cities = near_cities + len(Map[city]-cities) a.pop() if near_cities != 0: # for next_city in Map[city]: # if next_city not in cities: for next_city in (Map[city]-cities): a.append([number + 1, next_city, pro / near_cities]) else: # print(cities) # print("8888888",pro,number) sum = sum + pro * number print(sum)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int n, m; vector<vector<int> > G; vector<bool> mark; double dfs(int u, int p = -1) { mark[u] = false; double res = 0; int cnt = 0; for (int i = 0; i < G[u].size(); ++i) { int v = G[u][i]; if (mark[v] || v == p) continue; cnt++; res += dfs(v, u); } return (cnt ? res / cnt + 1 : 0); } int main() { cin >> n; m = n - 1; G.resize(n + 1); mark.assign(n + 1, false); for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; G[u].push_back(v); G[v].push_back(u); } cout << setprecision(7) << fixed << dfs(1); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> g[n]; for (int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; --u; --v; g[u].push_back(v); g[v].push_back(u); } double ans = 0; function<void(int, int, int, double)> dfs = [&](int u, int fa, int l, double p) { int sz = g[u].size(); if (u) { --sz; } if (sz == 0) { ans += (double)l * p; return; } for (auto v : g[u]) { if (v != fa) { dfs(v, u, l + 1, (double)p / double(sz)); } } }; dfs(0, 0, 0, 1); cout << fixed << setprecision(15) << ans << '\n'; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class C839 { static BufferedReader br; static StringTokenizer st; static PrintWriter pw; static String nextToken() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } static int nextInt() { return Integer.parseInt(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static String nextLine() throws IOException { return br.readLine(); } static char nextChar() throws IOException { return (char) br.read(); } public static void main(String[] args) { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); run(); pw.close(); } static ArrayList<Integer>[] graf; private static void run() { int n = nextInt(); graf = new ArrayList[n]; for (int i = 0; i < n; i++) { graf[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int x = nextInt() - 1; int y = nextInt() - 1; graf[x].add(y); graf[y].add(x); } pw.println(dfs(0, -1)); } private static double dfs(int v, int parent) { if (graf[v].size() == 1 && parent != -1) return 1; double ans = 0; for (int i = 0; i < graf[v].size(); i++) { if (graf[v].get(i) != parent) { ans += dfs(graf[v].get(i), v); } } if (parent == -1) return ans / Math.max(1,graf[v].size()); return ans / (graf[v].size() - 1) + 1; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
//package com.pb.codeforces.practice; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CF839C { public static double dfs(List<List<Integer>> adj, int u, int dt,int pt) { double ans = 0; int cnt = 0; for(int v : adj.get(u)) { if(v != pt) { cnt++; ans += dfs(adj,v,dt+1,u); } } return cnt == 0 ? 0 : (ans/cnt)+1; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); List<List<Integer>> adj = new ArrayList<>(); for(int i=0; i<n; i++) adj.add(new ArrayList<>()); for(int i=0; i<n-1; i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; adj.get(u).add(v); adj.get(v).add(u); } System.out.println(dfs(adj,0,0,-1)); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int N = int(1e5 + 5); vector<int> graph[N]; bool mark[N]; double dfs(int cur) { mark[cur] = 1; int cnt = 0; double len = 0; for (int city : graph[cur]) { if (mark[city]) continue; ++cnt; len += 1 + dfs(city); } if (cnt) return len / cnt; return 0; } int main() { std::ios::sync_with_stdio(0); std::cin.tie(0); int n; cin >> n; for (int i = 1, x, y; i < n; ++i) { cin >> x >> y; graph[x].push_back(y); graph[y].push_back(x); } cout << setprecision(10); cout << dfs(1); }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int MAXN = 100000 + 4; vector<int> G[MAXN]; int N, Pa[MAXN]; double D[MAXN]; double dp(int pa, int u) { double d = 0; int c = 0; for (auto v : G[u]) if (v != pa) d += 1 + dp(u, v), ++c; if (c) d /= c; return d; } int main() { int u, v; while (cin >> N) { for (int i = (0); i < (N); ++i) G[i].clear(); for (int i = (0); i < (N - 1); ++i) { cin >> u >> v; u--, v--; G[u].push_back(v), G[v].push_back(u); } double ans = dp(-1, 0); cout << setprecision(15) << ans << endl; } return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.*; import java.math.*; import java.util.*; public class Journey { static int INF = (int)(1e9); static long mod = (long)(1e9)+7; static long mod2 = 998244353; static long[] segtree; static char[] curans; static double ans; static String S; static ArrayList<Integer>[] graph; static boolean[] vis; public static void main(String[] args) { //Cash out /**/ FastScanner I = new FastScanner(); //Input OutPut O = new OutPut(); //Output int N = I.nextInt(); graph = new ArrayList[N+1]; vis = new boolean[N+1]; ans = 0.0; for (int i = 1; i<=N; i++) graph[i] = new ArrayList<Integer>(); for (int i = 0; i < N-1; i++) { int A = I.nextInt(); int B = I.nextInt(); graph[A].add(B); graph[B].add(A); } DFS(1,1.0,0.0); O.pln(ans); } public static void DFS(int now, double prob, double len) { double options = 0.0; vis[now]=true; for (int i = 0; i < graph[now].size(); i++) { int nbr = graph[now].get(i); if (!vis[nbr]) options++; } if (options==0.0) { //Leaf node case ans+=prob*len; }else { for (int i = 0; i < graph[now].size(); i++) { int nbr = graph[now].get(i); if (!vis[nbr]) { DFS(nbr,prob/options,len+1.0); } } } } public static double max(double a, double b) {return Math.max(a, b);} public static double min(double a, double b) {return Math.min(a, b);} public static long min(long a, long b) {return Math.min(a,b);} public static long max(long a, long b) {return Math.max(a,b);} public static int min(int a, int b) {return Math.min(a,b);} public static int max(int a, int b) {return Math.max(a,b);} public static long abs(long x) {return Math.abs(x);} public static long abs(int x) {return Math.abs(x);} public static long ceil(long num, long den) {long ans = num/den; if (num%den!=0) ans++; return ans;} public static long GCD(long a, long b) { if (a==0||b==0) return max(a,b); return GCD(min(a,b),max(a,b)%min(a,b)); } public static long FastExp(long base, long exp, long mod) { long ans=1; while (exp>0) { if (exp%2==1) ans*=base; exp/=2; base*=base; base%=mod; ans%=mod; } return ans; } public static long ModInv(long num,long mod) {return FastExp(num,mod-2,mod);} public static int pop(long x) { //Returns number of bits within a number int cnt = 0; while (x>0) { if (x%2==1) cnt++; x/=2; } return cnt; } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());}; double nextDouble() {return Double.parseDouble(next());} } static class OutPut{ PrintWriter w = new PrintWriter(System.out); void pln(double x) {w.println(x);w.flush();} void pln(boolean x) {w.println(x);w.flush();} void pln(int x) {w.println(x);w.flush();} void pln(long x) {w.println(x);w.flush();} void pln(String x) {w.println(x);w.flush();} void pln(char x) {w.println(x);w.flush();} void pln(StringBuilder x) {w.println(x);w.flush();} void pln(BigInteger x) {w.println(x);w.flush();} void p(int x) {w.print(x);w.flush();} void p(long x) {w.print(x);w.flush();} void p(String x) {w.print(x);w.flush();} void p(char x) {w.print(x);w.flush();} void p(StringBuilder x) {w.print(x);w.flush();} void p(BigInteger x) {w.print(x);w.flush();} void p(double x) {w.print(x);w.flush();} void p(boolean x) {w.print(x);w.flush();} } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; public class QA { static long MOD = 1000000007; static boolean b[], b1[], check; static ArrayList<Integer>[] amp, pa; static ArrayList<Pair>[] amp1; static ArrayList<Pair>[][] damp; static int left[],right[],end[],sum[],dist[],cnt[],start[],color[],parent[],prime[],size[]; static int ans = 0,k; static int p = 0; static FasterScanner sc = new FasterScanner(System.in); static Queue<Integer> q = new LinkedList<>(); static BufferedWriter log; static HashSet<Pair> hs; static HashMap<Pair,Integer> hm; static PriorityQueue<Integer> pri[]; static ArrayList<Integer>[] level; static Stack<Integer> st; static boolean boo[][]; static Pair prr[]; static long parent1[],parent2[],size1[],size2[],arr1[],SUM[],lev[], fibo[]; static int arr[], ver[][]; static private PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { soln(); } catch (Exception e) { System.out.println(e); } } }, "1", 1 << 26).start(); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } static int dp[][]; static int N,K,T,A,B; static long time; static int cost[][]; static boolean b11[]; static HashMap<Integer,Integer> h = new HashMap<>(); static HashSet<Pair> chec; static long ans1; static long ans2; static int BLOCK, MAX = 200000; static double pi = Math.PI; static int Arr[], Brr[], pow[], M; static long fact[] = new long[100000+1]; static HashMap<Integer,Long> hm1; static HashSet<Integer> hs1[], hs2[]; static String[] str2; static char[] ch1, ch2; static int[] s,f,D; static int tf,ts; //static PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); public static void soln() throws IOException { //FasterScanner sc = new FasterScanner(new FileInputStream("C:\\Users\\Admin\\Desktop\\QAL2.txt")); //PrintWriter log1 = new PrintWriter("C:\\Users\\Admin\\Desktop\\input01"); //PrintWriter log = new PrintWriter("C:\\Users\\Admin\\Desktop\\output00"); log = new BufferedWriter(new OutputStreamWriter(System.out)); int n = sc.nextInt(); amp = (ArrayList<Integer>[]) new ArrayList[n]; for(int i = 0; i < n ;i++) amp[i] = new ArrayList<>(); buildGraph(n-1); b = new boolean[n]; dist = new int[n]; p = 0; System.out.println( dfs(0,-1)); log.close(); } private static double dfs(int cur,int prev){ double r=0,n=0; for(int i : amp[cur]){ if(i!=prev){ r+=(1+dfs(i,cur)); n++; } } if(n!=0){ r=r/n; } return r; } static double fa1 = 0; static int fa = -1; static long nCr1(int n, int r){ if(n<r) return 0; return (((fact[n] * modInverse(fact[n-r], MOD))%MOD)*modInverse(fact[r], MOD))%MOD; } static class Node{ Node arr[] = new Node[2]; int cnt[] = new int[2]; } public static class Trie{ Node root; public Trie(){ root = new Node(); } public void insert(String x){ Node n = root; for(int i = 0;i < x.length() ;i++){ int a1 = x.charAt(i)-'0'; if(n.arr[a1]!=null){ n.cnt[a1]++; n = n.arr[a1]; continue; } n.arr[a1] = new Node(); n.cnt[a1]++; n = n.arr[a1]; } } public void delete(String x){ Node n = root; for(int i = 0;i < x.length() ;i++){ int a1 = x.charAt(i)-'0'; if(n.cnt[a1]==1){ n.arr[a1] = null; return; } else { n.cnt[a1]--; n = n.arr[a1]; } } } public long get(String x){ Node n = root; long ans = 0; for(int i = 0;i < x.length() ;i++){ int a1 = '1' - x.charAt(i); if(n.arr[a1]!=null){ ans += Math.pow(2, 30-i); n = n.arr[a1]; } else n = n.arr[1-a1]; // System.out.println(ans); } return ans; } } public static class FenwickTree { int[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new int[size + 1]; } public int rsq(int ind) { assert ind > 0; int sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public int rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, int value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static double power(double x, long y) { if (y == 0) return 1; double p = power(x, y/2); p = (p * p); return (y%2 == 0)? p : (x * p); } static void Bfs(int x){ q.add(x); b[x] = true; while(!q.isEmpty()){ int y = q.poll(); b[y] = true; for(int p:hs2[y]){ if(!b[p]){ if(!hs1[y].contains(p)) dist[p] = dist[y]-1; else dist[p] = dist[y]+1; q.add(p); } } } } static int Dfs(int x, int val){ b[x] = true; for(int p:hs2[x]){ if(!b[p]){ if(!hs1[x].contains(p)) val++; val += Dfs(p,0); } } return val; } static long nCr(int n, int r){ if(n<r) return 0; else return (((fact[n]*modInverse(fact[r], MOD))%MOD)*modInverse(fact[n-r], MOD))%MOD; } static void dfs1(int x, int p){ arr1[x] += lev[x]; for(int v:amp[x]){ if(v!=p){ dfs1(v,x); } } } static void bfs(){ q = new LinkedList<>(); q.add(0); while(!q.isEmpty()){ int y = q.poll(); b[y] = true; level[dist[y]].add(start[y]); for(int x:amp[y]){ if(!b[x]){ q.add(x); dist[x] = 1+dist[y]; } } } } static void bfs(int x){ } public static void seive(int n){ b = new boolean[(n+1)]; Arrays.fill(b, true); b[1] = true; for(int i = 2;i*i<=n;i++){ if(b[i]){ for(int p = 2*i;p<=n;p+=i){ b[p] = false; } } } /*for(int i = 2;i<=n;i++){ if(b[i]) prime[i] = i; }*/ } static class Graph{ int vertex; int weight; Graph(int v, int w){ vertex = v; weight = w; } } static class Pair implements Comparable<Pair> { int u; int v; int ans; public Pair(){ u = 0; v = 0; } public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { return Objects.hash(); } public boolean equals(Object o) { Pair other = (Pair) o; return ((u == other.u && v == other.v && ans == other.ans)); } public int compareTo(Pair other) { //return Double.compare(ans, other.ans); return Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static void buildGraph(int n){ for(int i =0;i<n;i++){ int x = sc.nextInt()-1, y = sc.nextInt()-1; amp[x].add(y); amp[y].add(x); } } public static int getParent(long x){ while(parent[(int) x]!=x){ parent[ (int) x] = parent[(int) parent[ (int) x]]; x = parent[ (int) x]; } return (int) x; } static long min(long a, long b, long c){ if(a<b && a<c) return a; if(b<c) return b; return c; } /* static class Pair3{ int x, y ,z; Pair3(int x, int y, int z){ this.x = x; this.y = y; this.z = z; } }*/ static void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat,M,lps); int i = 0; // index for txt[] while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { // parent.add((i-j)); j = lps[j-1]; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j-1]; else i = i+1; } } } static void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } private static void permutation(String prefix, String str) { int n = str.length(); if (n == 0); //hs.add(prefix); else { for (int i = 0; i < n; i++) permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n)); } } public static void buildTree(int n){ int arr[] = sc.nextIntArray(n); for(int i = 0;i<n;i++){ int x = arr[i]-1; amp[i+1].add(x); amp[x].add(i+1); } } static class SegmentTree { boolean st[]; boolean lazy[]; SegmentTree(int n) { int size = 4 * n; st = new boolean[size]; Arrays.fill(st, true); lazy = new boolean[size]; Arrays.fill(lazy, true); //build(0, n - 1, 1); } /*long[] build(int ss, int se, int si) { if (ss == se) { st[si][0] = 1; st[si][1] = 1; st[si][2] = 1; return st[si]; } int mid = (ss + se) / 2; long a1[] = build(ss, mid, si * 2), a2[] = build(mid + 1, se, si * 2 + 1); long ans[] = new long[3]; if (arr[mid] < arr[mid + 1]) { ans[1] = Math.max(a2[1], Math.max(a1[1], a1[2] + a2[0])); if (a1[1] == (mid - ss + 1)) ans[0] = ans[1]; else ans[0] = a1[0]; if (a2[2] == (se - mid)) ans[2] = ans[1]; else ans[2] = a2[2]; } else { ans[1] = Math.max(a1[1], a2[1]); ans[0] = a1[0]; ans[2] = a2[2]; } st[si] = ans; return st[si]; }*/ void update(int si, int ss, int se, int idx, long x) { if (ss == se) { //arr[idx] += val; st[si]=false; } else { int mid = (ss + se) / 2; if(ss <= idx && idx <= mid) { update(2*si, ss, mid, idx, x); } else { update(2*si+1, mid+1, se, idx, x); } st[si] = st[2*si]|st[2*si+1]; } } /*boolean get(int qs, int qe, int ss, int se, int si){ if(qs>se || qe<ss) return 0; if (qs <= ss && qe >= se) { return st[si]; } int mid = (ss+se)/2; return get(qs, qe, ss, mid, si * 2)+get(qs, qe, mid + 1, se, si * 2 + 1); }*/ void updateRange(int node, int start, int end, int l, int r, boolean val) { if(!lazy[node]) { // This node needs to be updated st[node] = lazy[node]; // Update it if(start != end) { lazy[node*2] = lazy[node]; // Mark child as lazy lazy[node*2+1] = lazy[node]; // Mark child as lazy } lazy[node] = true; // Reset it } if(start > end || start > r || end < l) // Current segment is not within range [l, r] return; if(start >= l && end <= r) { // Segment is fully within range st[node] = val; if(start != end) { // Not leaf node lazy[node*2] = val; lazy[node*2+1] = val; } return; } int mid = (start + end) / 2; updateRange(node*2, start, mid, l, r, val); // Updating left child updateRange(node*2 + 1, mid + 1, end, l, r, val); // Updating right child st[node] = st[node*2] | st[node*2+1]; // Updating root with max value } boolean queryRange(int node, int start, int end, int l, int r) { if(start > end || start > r || end < l) return false; // Out of range if(!lazy[node]) { // This node needs to be updated st[node] = lazy[node]; // Update it if(start != end) { lazy[node*2] = lazy[node]; // Mark child as lazy lazy[node*2+1] = lazy[node]; // Mark child as lazy } lazy[node] = true; // Reset it } if(start >= l && end <= r) // Current segment is totally within range [l, r] return st[node]; int mid = (start + end) / 2; boolean p1 = queryRange(node*2, start, mid, l, r); // Query left child boolean b = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child return (p1 | b); } void print() { for (int i = 0; i < st.length; i++) { System.out.print(st[i]+" "); } System.out.println(); } } static int convert(int x){ int cnt = 0; String str = Integer.toBinaryString(x); //System.out.println(str); for(int i = 0;i<str.length();i++){ if(str.charAt(i)=='1'){ cnt++; } } int ans = (int) Math.pow(3, 6-cnt); return ans; } static class Node2{ Node2 left = null; Node2 right = null; Node2 parent = null; int data; } static boolean check(char ch[][], int i, int j){ if(ch[i][j]=='O') return false; char c = ch[i][j]; ch[i][j] = 'X'; if(c=='X'){ if(i>=4){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j]!='X'){ if(ch[i-x][j]!='.') break;else l++;} } if(x==5 && l<=1) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i-x][j-x]!='X'){ if(ch[i-x][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j+x]!='X'){ if(ch[i-x][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } } if(i<=5){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j]!='X'){ if(ch[i+x][j]!='.') break; else l++;} } if(x==5 && l<=1) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i+x][j-x]!='X'){ if(ch[i+x][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j+x]!='X'){ if(ch[i+x][j+x]!='.') break; else l++;} } if(x==5 && l<=1) return true; } } } else{ if(i>=4){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j]!='X'){ if(ch[i-x][j]!='.') break;else l++;} } if(x==5 && l<=0) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i-x][j-x]!='X'){ if(ch[i-x][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i-x][j+x]!='X'){ if(ch[i-x][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } } if(i<=5){ int x = 0; int l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j]!='X'){ if(ch[i+x][j]!='.') break; else l++;} } if(x==5 && l<=0) return true; l = 0; if(j>=4){ for(x = 0;x<=4;x++){ if(ch[i+x][j-x]!='X'){ if(ch[i+x][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l =0; for(x = 0;x<=4;x++){ if(ch[i][j-x]!='X'){ if(ch[i][j-x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } if(j<=5){ l = 0; for(x = 0;x<=4;x++){ if(ch[i][j+x]!='X'){ if(ch[i][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; l = 0; for(x = 0;x<=4;x++){ if(ch[i+x][j+x]!='X'){ if(ch[i+x][j+x]!='.') break; else l++;} } if(x==5 && l<=0) return true; } } } ch[i][j] = c; return false; } static class BinarySearchTree{ Node2 root = null; int height = 0; int max = 0; int cnt = 1; ArrayList<Integer> parent = new ArrayList<>(); HashMap<Integer, Integer> hm = new HashMap<>(); public void insert(int x){ Node2 n = new Node2(); n.data = x; if(root==null){ root = n; } else{ Node2 temp = root,temb = null; while(temp!=null){ temb = temp; if(x>temp.data) temp = temp.right; else temp = temp.left; } if(x>temb.data) temb.right = n; else temb.left = n; n.parent = temb; parent.add(temb.data); } } public Node2 getSomething(int x, int y, Node2 n){ if(n.data==x || n.data==y) return n; else if(n.data>x && n.data<y) return n; else if(n.data<x && n.data<y) return getSomething(x,y,n.right); else return getSomething(x,y,n.left); } public Node2 search(int x,Node2 n){ if(x==n.data){ max = Math.max(max, n.data); return n; } if(x>n.data){ max = Math.max(max, n.data); return search(x,n.right); } else{ max = Math.max(max, n.data); return search(x,n.left); } } public int getHeight(Node2 n){ if(n==null) return 0; height = 1+ Math.max(getHeight(n.left), getHeight(n.right)); return height; } } static long findDiff(long[] arr, long[] brr, int m){ int i = 0, j = 0; long fa = 1000000000000L; while(i<m && j<m){ long x = arr[i]-brr[j]; if(x>=0){ if(x<fa) fa = x; j++; } else{ if((-x)<fa) fa = -x; i++; } } return fa; } public static long max(long x, long y, long z){ if(x>=y && x>=z) return x; if(y>=x && y>=z) return y; return z; } static long modInverse(long a, long mOD2){ return power(a, mOD2-2, mOD2); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y/2, m) % m; p = (p * p) % m; return (y%2 == 0)? p : (x * p) % m; } static long d,x,y; public static void extendedEuclidian(long a, long b){ if(b == 0) { d = a; x = 1; y = 0; } else { extendedEuclidian(b, a%b); int temp = (int) x; x = y; y = temp - (a/b)*y; } } public static long gcd(long n, long m){ if(m!=0) return gcd(m,n%m); else return n; } static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static class FasterScanner { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public FasterScanner(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; class Node { public: int loc; long double ans; vector<Node *> nbh; Node(int pos) { loc = pos; ans = -1; } }; vector<Node *> Graph; vector<int> v; long double soln(Node *curr) { int sz = 0; long double temp = 0, fact; v[curr->loc] = 1; if (curr->ans != -1) return curr->ans; for (int i = 0; i < curr->nbh.size(); ++i) { if (v[curr->nbh[i]->loc] == 0) sz = sz + 1; } if (sz == 0) { curr->ans = 0; return 0; } else { fact = (long double)(1) / (double)(sz); for (int i = 0; i < curr->nbh.size(); ++i) { if (v[curr->nbh[i]->loc] == 0) { temp = temp + fact * (soln(curr->nbh[i]) + 1); } } curr->ans = temp; } return curr->ans; } int main(int argc, char const *argv[]) { Graph.clear(); int n; cin >> n; Graph.resize(n + 1); v.resize(n + 1); for (int i = 1; i <= n; ++i) { Graph[i] = new Node(i); } for (int i = 0; i < n - 1; ++i) { int src, des; cin >> src >> des; Graph[src]->nbh.push_back(Graph[des]); Graph[des]->nbh.push_back(Graph[src]); } long double answer = soln(Graph[1]); printf("%.15Lf\n", answer); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import sys def main(): n = int(input()) if n == 1: print(0) return x = [[] for i in range(n)] for i in range(n - 1): a, b = map(int, sys.stdin.readline().split()) x[a - 1].append(b - 1) x[b - 1].append(a - 1) isl = [False] * n for i in range(1, n): if len(x[i]) == 1: isl[i] = True u = [False] * n u[0] = True q = [(0, 0, 1 / len(x[0]))] a = 0 while len(q) != 0: c, s, t = q.pop() for i in x[c]: if not u[i]: if isl[i]: a += (s + 1) * t else: q.append((i, s + 1, t / (len(x[i])-1))) u[i] = True print(a) main()
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class j6 implements Runnable { long md=1000000007; long power(long x, long y, long p) { long res = 1; x=(x % p); while (y > 0) { if((y & 1)==1) res = ((res%p) * (x%p))% p; y =y >> 1; x =((x%p)*(x%p))%p; } return res; } long gcd(long a,long b) { if(a==0) return b; else return gcd(b%a,a); } public void run(){ InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n=in.nextInt(); ArrayList<Integer> al[]=new ArrayList[n+1]; int[] vis=new int[n+1]; int dis[]=new int[n+1]; double prob[]=new double[n+1]; for(int i=1;i<=n;i++) { al[i]=new ArrayList<Integer>(); } for(int i=1;i<=n-1;i++) { int a=in.nextInt(); int b=in.nextInt(); al[a].add(b); al[b].add(a); } dis[1]=0; prob[1]=1; double p=1; Queue<Integer> qu=new LinkedList<>(); qu.add(1); vis[1]=1; while(!qu.isEmpty()) { int x=qu.poll(); if(x!=1) p=prob[x]*((double)1/(al[x].size()-1)); else p=prob[x]*((double)1/(al[x].size())); for(int i=0;i<al[x].size();i++) { int y=al[x].get(i); if(vis[y]==0) { prob[y]=p; dis[y]=dis[x]+1; vis[y]=1; qu.add(y); } } } double sum=0; if(n>2) { for(int i=1;i<=n;i++) { //w.println(i+" "+dis[i]+" "+prob[i]); if(i!=1 && al[i].size()==1) { sum+=prob[i]*dis[i]; } } w.println(sum); } else if(n==2) { w.println(dis[2]*prob[2]); } else if(n==1) w.println(prob[1]*dis[1]); w.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new j6(),"j6",1<<26).start(); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<int> v[100010]; bool ch[100010]; bool s[100010]; int n; double ans = 0.0; int main() { scanf(" %d", &n); for (int i = 0; i < n - 1; i++) { int l, r; scanf(" %d %d", &l, &r); l--; r--; v[l].push_back(r); v[r].push_back(l); } for (int i = 0; i < n; i++) ch[i] = false; if (n == 2) { printf("1.0\n"); return 0; } queue<pair<int, pair<int, double> > > q; pair<int, pair<int, double> > p; p.first = 0; p.second.first = 0; p.second.second = (double)1; q.push(p); while (!q.empty()) { p = q.front(); q.pop(); if (ch[p.first] == true) continue; ch[p.first] = true; if (v[p.first].size() == 1 && p.first != 0) { ans += p.second.first * p.second.second; continue; } int temp = 0; for (int i = 0; i < v[p.first].size(); i++) { pair<int, pair<int, double> > pp; pp.first = v[p.first][i]; pp.second.first = p.second.first + 1; if (p.first != 0) pp.second.second = p.second.second * (double)1 / (v[p.first].size() - 1); else pp.second.second = p.second.second * (double)1 / v[p.first].size(); q.push(pp); } } printf("%lf\n", ans); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Journey2 implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static double BFS(ArrayList<Integer> al[], int n) { double total=0; LinkedList<Pair> queue = new LinkedList<Pair>(); queue.add(new Pair(1,(double)0,(double)1)); boolean visited[]= new boolean[n+1]; while(!queue.isEmpty()) { Pair p=queue.pollFirst(); int x=p.x; double d=p.d; double pro=p.pro; visited[x]=true; double counter=0; for(int i=0;i<al[x].size();++i) { if(!visited[al[x].get(i)]) counter++; } if(counter==0) { total+=(d*pro); } else { pro*=((double)1/counter); for(int i=0;i<al[x].size();++i) { if(!visited[al[x].get(i)]) { queue.add(new Pair(al[x].get(i),d+1,pro)); } } } } return total; } public static void main(String args[]) throws Exception { new Thread(null, new Journey2(),"Journey2",1<<27).start(); } // **just change the name of class from Main to reuquired** public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n=sc.nextInt(); ArrayList<Integer> al[]= new ArrayList[n+1]; for(int i=0;i<=n;++i) al[i]= new ArrayList<Integer>(); for(int i=0;i<n-1;++i) { int u=sc.nextInt(); int v=sc.nextInt(); al[u].add(v); al[v].add(u); } w.println(BFS(al,n)); System.out.flush(); w.close(); } } class Pair { int x; double d; double pro; Pair(int p, double dist, double probability) { x=p; d=dist; pro=probability; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import javafx.util.Pair; import java.io.*; import java.util.*; public class Main { class FastScanner { private BufferedReader bufferedReader; private StringTokenizer stringTokenizer; public FastScanner(InputStream inputStream){ bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()){ try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException ignored){} } return stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } private FastScanner scanner; private PrintWriter printer; Main(InputStream scanner, PrintWriter printWriter) { this.scanner = new FastScanner(scanner); this.printer = printWriter; } int gcd (int a, int b) { if (b == 0) return a; return gcd(b, a % b); } boolean isPrime(int n) { for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } List<Integer>prostMnoj(int n) { ArrayList<Integer> r = new ArrayList<>(); int p = 2; while(n != 1) { while(n % p == 0) { n /= p; r.add(p); } p++; while(!isPrime(p)) { p++; } } return r; } List<Integer>allMnoj(List<Integer>a) { ArrayList<Integer>r = new ArrayList<>(); boolean b[] = new boolean[a.size() + 1]; while(!b[0]) { int i = a.size(); while(b[i]) { i--; } b[i++] = true; while(i<b.length) { b[i++] = false; } int m = 1; for (i = 1; i < b.length; i++) { if (b[i]) { m*=a.get(i-1); } } r.add(m); } return r; } double a(long n) { return (180.0 * (n-2)) / n; } void next (int a[]) { for (int i = a.length - 2; i >= 0; i--) { if (a[i] < a[i+1]) { for (int j = a.length - 1;; j--) { if (a[j] > a[i]) { int t = a[i]; a[i] = a[j]; a[j] = t; break; } } for (int j = i + 1; j <= i + ((a.length - 1) - i) / 2; j++) { int t = a[j]; int k = (a.length - 1) - (j - (i + 1)); a[j] = a[k]; a[k] = t; } break; } } } int fact(int n) { if (n == 1) return 1; return n * fact(n - 1); } int dfs(List<List<Integer>>g, int v, boolean used[]) { if (used[v]) return 0; used[v] = true; int sum = 1; for (int i = 0; i < g.get(v).size(); i++) { sum += dfs(g, g.get(v).get(i), used); } return sum; } int find(List<List<Integer>>g, int v, int x, boolean used[]) { if (used[v]) return -1; used[v] = true; if (g.get(v).contains(x)) return v; for (int i = 0; i < g.get(v).size(); i++) { int res = find(g, g.get(v).get(i), x, used); if (res != -1) return res; } return -1; } int dp[] = new int[101]; { Arrays.fill(dp, -1); } int[] ms(int n) { int dp[] = new int[n + 1]; int tp[] = new int[n + 1]; dp[1] = 0; tp[1] = 1; for (int i = 2; i <= n; i++) { int t = i - 1; dp[i] = dp[i - 1]; if (i % 2 == 0 && dp[i / 2] < dp[i]) { dp[i] = dp[i / 2]; t = i / 2; } if (i % 3 == 0 && dp[i / 3] < dp[i]) { dp[i] = dp[i / 3]; t = i / 3; } dp[i]++; tp[i] = t; } printer.println(dp[n]); int t = n; StringBuilder s = new StringBuilder(); while (t != 1) { s.insert(0, t); s.insert(0, " "); t = tp[t]; } s.insert(0, "1"); printer.println(s); return dp; } double gg(List<List<Integer>>g, boolean used[], int v) { List<Integer> gv = g.get(v); used[v] = true; if (gv.isEmpty()) return 0; if (gv.size() == 1 && used[gv.get(0)]) { return 0; } int k = 0; double sum = 0; for (int i = 0; i < gv.size(); i++) { if (!used[gv.get(i)]) { sum += gg(g, used, gv.get(i)); k++; } } return sum / k + 1; } void run() { int n = scanner.nextInt(); List<List<Integer>>g = new ArrayList<>(); for (int i = 0; i < n; i++) { g.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int x = scanner.nextInt() - 1; int y = scanner.nextInt() - 1; g.get(x).add(y); g.get(y).add(x); } printer.println(gg(g, new boolean[n], 0)); printer.flush(); printer.close(); } public static void main(String [] args) { long start = System.currentTimeMillis(); new Main(System.in, new PrintWriter(System.out)).run(); long finish = System.currentTimeMillis(); System.err.println(finish - start + "ms"); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import sys sys.setrecursionlimit(1000000) n = int(input()) lis = [ [] for _ in range(n) ] lis[0].append(0) for k in range(1,n): a, i = map(int,input().split()) lis[a-1].append(i-1) lis[i-1].append(a-1) def cnt(root, count, div, zero): stack = [(root, count, div, zero)] while(stack): spot, depth, prb,origin = stack.pop() if(visited[spot]): continue visited[spot] = True for k in lis[spot]: if(k != origin): prby[k] = (depth+1)/(prb*(len(lis[spot])-1)) stack.append((k, depth+1, prb*(len(lis[spot])-1), spot)) prby = [0]*n visited = [False]*n esp = 0 cnt(0, 0, 1, 0) for k in range(n-1,0, -1): if(len(lis[k])==1): esp+=prby[k] print(esp)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
from sys import stdin, stdout, setrecursionlimit import threading # tail-recursion optimization # In case of tail-recusion optimized code, have to use python compiler. # Otherwise, memory limit may exceed. # declare the class class Tail_Recursion_Optimization class Tail_Recursion_Optimization: def __init__(self, recursion_limit, stack_size): setrecursionlimit(recursion_limit) threading.stack_size(stack_size) class SOLVE: def dfs(self, child, parent, node): total = 0 for v in node[child]: if v != parent: total += self.dfs(v, child, node) + 1 return ((total / (len(node[child]) - (1 if parent else 0))) if total else 0) def solve(self): R = stdin.readline #f = open('input.txt');R = f.readline W = stdout.write n = int(R()) node = [[] for i in range(n+1)] for _ in range(n-1): u, v = [int(x) for x in R().split()] node[u].append(v) node[v].append(u) print(self.dfs(1, 0, node)) return 0 def main(): s = SOLVE() s.solve() Tail_Recursion_Optimization(10**7, 2**26) threading.Thread(target=main).start()
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
from collections import defaultdict graph = defaultdict(list) n = int(input()) for _ in range(n-1): u,v = list(map(int,input().split())) graph[u-1].append(v-1) graph[v-1].append(u-1) distances = {} prob = [0 for i in range(n)] q = [(0,0)] prob[0] = 1 visited = [False for i in range(n)] visited[0] = True while q!=[]: node,dist = q[0] q.pop(0) leaf = True m = 0 for i in graph[node]: if visited[i]==False: m+=1 for j in graph[node]: if visited[j]==False: visited[j] = True leaf = False prob[j] = prob[node]/m q.append((j,dist+1)) if leaf: distances[node] = dist # print(prob) # print(distances) ans = 0 for i in distances: ans+=prob[i]*distances[i] print(ans)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int n; vector<vector<int>> g; int leaf_cnt; vector<int> dst; vector<char> is_leaf; long double dfs(int x, int prev = -1) { vector<long double> ans; for (int to : g[x]) { if (to == prev) continue; ans.push_back(dfs(to, x)); } if (ans.empty()) return 0; return accumulate(ans.begin(), ans.end(), 0.0) / ans.size() + 1; } int main() { ios_base::sync_with_stdio(0); cin >> n; g.resize(n + 1); dst.resize(n + 1); is_leaf.resize(n + 1); for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; g[x].push_back(y); g[y].push_back(x); } cout.precision(10); cout << fixed << dfs(1); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws IOException{ FastScanner in = new FastScanner(System.in); PrintWriter out= new PrintWriter(System.out); int n= in.nextInt(); ArrayList<Integer>[] adj= new ArrayList[n]; for (int i = 0; i < adj.length; i++) { adj[i]= new ArrayList<>(); } for (int i = 0; i < n-1; i++) { int a= in.nextInt()-1; int b= in.nextInt()-1; adj[a].add(b); adj[b].add(a); } ArrayDeque<p> q= new ArrayDeque<>(); q.offer(new p(0, 1L, 0, -1)); double tot=0; while(!q.isEmpty()){ p cur= q.poll(); int num=0; double len= adj[cur.node].size(); if(cur.node!=0) len--; for (int nex: adj[cur.node]) { if(nex== cur.parent) continue; q.offer(new p(nex, cur.p/len, cur.d+1, cur.node)); num++; } if(num==0){ double a= cur.d*1.0; double b= cur.p*1.0; //System.out.println(a+" " +b); tot+= (a*b); } } System.out.printf("%.8f\n",tot); } public static long gcd(long p, long q) { if (q == 0) return p; else return gcd(q, p % q); } static class p{ int node; double p; int d; int parent; public p(int a, double b, int c, int e){ node= a; p= b; d= c; parent= e; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public String next() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); return next(); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } } /* 8 1 2 1 3 2 4 2 5 2 6 3 7 7 8 7 1 2 1 3 1 4 2 5 2 7 3 6 6 1 2 1 3 3 4 3 5 5 6 5 7 */
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rishabhdeep Singh */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { List<Integer>[] adj; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt(), v = in.nextInt(); adj[u - 1].add(v - 1); adj[v - 1].add(u - 1); } out.println(dfs(0, -1)); } private double dfs(int index, int parent) { int cnt = 0; double sum = 0; for (int child : adj[index]) { if (child != parent) { cnt++; sum += dfs(child, index) + 1; } } if (cnt == 0) return 0; return sum / cnt; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; unordered_map<int, vector<int> > g; unordered_map<int, bool> visited; void addedge(int u, int v) { g[u].push_back(v); g[v].push_back(u); } double dfs(int i, int v) { double opt = g[i].size(); if (v != 0) opt -= 1; double cnt = 0; for (auto u : g[i]) { if (u != v) { cnt += (double)(dfs(u, i) + 1.0) / (opt); } } return cnt; } int main() { int n; cin >> n; int i, j, a, b; for (i = 1; i <= n - 1; ++i) { cin >> a >> b; addedge(a, b); } cout << fixed << setprecision(15) << dfs(1, 0); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
# Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n=int(input()) d=[[]for _ in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) d[a].append(b) d[b].append(a) d[1].append(1) vis=[0]*(n+1) stack=[(1,1,0)] ans=0 while stack: zz=stack.pop() if vis[zz[0]]: continue vis[zz[0]]=1 pp=len(d[zz[0]]) if pp==1: ans+=(zz[1]*zz[2]) else: for item in d[zz[0]]: if vis[item]==0: stack.append((item,zz[1]/(pp-1),zz[2]+1)) print("{:.7f}".format(ans)) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main()
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.*; import java.util.*; import java.text.*; public class C{ public static void main(String[]arg) throws IOException{ new C().read(); } City[]cities; double[]a; boolean[]vis; public void read() throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int n,N,u,v; N = Integer.parseInt(in.readLine()); vis = new boolean[N]; init(N); a = new double[N]; for(n = 1; n < N; n++){ st = new StringTokenizer(in.readLine()); u = Integer.parseInt(st.nextToken()) - 1; v = Integer.parseInt(st.nextToken()) - 1; cities[u].toUnion(v); cities[v].toUnion(u); } cities[0].cnt++; double ans = countLeaves(0,0,1); DecimalFormat df = new DecimalFormat("0.000000"); System.out.println(df.format(ans)); } double countLeaves(int u, int d, double px){ double ans = 0; int i,cnt = 0,v; vis[u] = true; for(i = 0; i < cities[u].roads.size(); i++){ v = cities[u].roads.get(i); if(!vis[v]){ cnt++; ans += countLeaves(v, d + 1, ((px)*(1.0/(cities[u].cnt-1)))); } } if(cnt == 0){ ans = d*px; } return ans; } void init(int N){ cities = new City[N]; for(int i = 0; i < N; i++) cities[i] = new City(); } public class City{ ArrayList<Integer> roads; int cnt; public City(){ cnt = 0; roads = new ArrayList<Integer>(); } public void toUnion(int city){ cnt++; roads.add(city); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
//Journey import java.io.*; import java.util.*; //semi-tutorial public class C839b{ public static double answer = 0.0; public static ArrayList<ArrayList<Integer>> roads; public static void main(String[] args)throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(f.readLine()); roads = new ArrayList<ArrayList<Integer>>(n); for(int k = 0; k < n+1; k++) roads.add(new ArrayList<Integer>()); for(int k = 0; k < n-1; k++){ StringTokenizer st = new StringTokenizer(f.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; roads.get(a).add(b); roads.get(b).add(a); } double answer = dfs(0,-1); if(n==1) out.println(0.0); else if(answer>0) out.println(answer); else out.println(-1); out.close(); } public static double dfs(int cur, int parent){ double sum = 0.0; for(int i : roads.get(cur)){ if(i!=parent){ sum+=dfs(i,cur)+1; } } if(sum==0.0) return 0.0; if(parent==-1) return sum/roads.get(cur).size(); else return sum/(roads.get(cur).size()-1); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<long long int> adj[200005]; long long int n; long double ans = 0; long double childavg(long long int s, long long int par) { long double child = 0; long double sum = 0; for (auto u : adj[s]) { if (u != par) { sum = sum + childavg(u, s); child++; } } if (child == 0) return 0; return 1.0 + (sum) / child; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int t, i, j; t = 1; while (t--) { cin >> n; for (i = 0; i < n - 1; i++) { long long int x, y; cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } cout << fixed << setprecision(12) << childavg(1, -1) << "\n"; } return (0); }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; long long n, m, a[100100], h[100100], t, r; long double ans; vector<long long> v[100100]; void dfs(long long x, long double y, long double k) { h[x] = 1; if (a[x] == 0) ans += k / y; for (int i = 0; i < v[x].size(); i++) { if (h[v[x][i]] == 0) { a[v[x][i]]--; dfs(v[x][i], y * a[x], k + 1); a[v[x][i]]++; } } h[x] = 0; } int main() { cout << fixed << setprecision(6); cin >> n; for (int i = 0; i < n - 1; i++) { cin >> t >> r; a[t]++; a[r]++; v[t].push_back(r); v[r].push_back(t); } dfs(1, 1, 0); cout << ans; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int n, u, v; vector<int> adj[100001]; double dfs(int k, int kk) { if ((int)(adj[kk]).size() == 1 && k) return 0; double ans = 0, res = 0; for (auto i : adj[kk]) { if (i == k) continue; ans += dfs(kk, i); res++; } return (ans / res) + 1.0; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; if (n == 1) return printf("%0.16f", 0), 0; for (int i = 1; i < n; i++) { cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } printf("%0.16f", dfs(0, 1)); }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<int> G[100005]; int vis[100005]; double ans = 0; void dfs(int u, double p) { vis[u] = 1; int cnt = 0; for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if (!vis[v]) { cnt++; } } if (cnt == 0) return; for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if (!vis[v]) { dfs(v, p * 1.0 / (double)cnt); } } if (cnt != 0) ans += p; } int main() { memset(vis, 0, sizeof vis); int n; scanf("%d", &n); for (int i = 1; i < n; i++) { int u, v; scanf("%d %d", &u, &v); G[u].push_back(v); G[v].push_back(u); } dfs(1, 1.0); printf("%.15lf\n", ans); }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
# Template 1.0 import sys, re, math from collections import deque, defaultdict, Counter, OrderedDict from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians from heapq import heappush, heappop, heapify, nlargest, nsmallest def STR(): return list(input()) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) def list2d(a, b, c): return [[c] * b for i in range(a)] def sortListWithIndex(listOfTuples, idx): return (sorted(listOfTuples, key=lambda x: x[idx])) def sortDictWithVal(passedDic): temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))[::-1] toret = {} for tup in temp: toret[tup[0]] = tup[1] return toret def sortDictWithKey(passedDic): return dict(OrderedDict(sorted(passedDic.items()))) sys.setrecursionlimit(10 ** 9) INF = float('inf') mod = 10 ** 9 + 7 n = INT() graph = defaultdict(list) for _ in range(n-1): t1,t2 = MAP() graph[t1].append(t2) graph[t2].append(t1) visited = [False]*(n+1) q = deque([(1, 0, 1)]) #nodeNum, distance, probab leafLengths = [] total = 0 while(q): popped = q.popleft() node = popped[0] dis = popped[1] probab = popped[2] flag = 1 visited[node] = True numChild = len(graph[node]) if(node!=1): numChild -= 1 for child in graph[node]: if(visited[child]==False): q.append((child, dis + 1, probab/numChild)) flag = 0 #leaf node: if(flag==1): leafLengths.append((dis, probab)) total+=1 # print(total, leafLengths) ans = 0 for el in leafLengths: ans+=el[0]*el[1] print(ans)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import sys;readline = sys.stdin.readline def i1(): return int(readline()) def nl(): return [int(s) for s in readline().split()] def nn(n): return [int(readline()) for i in range(n)] def nnp(n,x): return [int(readline())+x for i in range(n)] def nmp(n,x): return (int(readline())+x for i in range(n)) def nlp(x): return [int(s)+x for s in readline().split()] def nll(n): return [[int(s) for s in readline().split()] for i in range(n)] def mll(n): return ([int(s) for s in readline().split()] for i in range(n)) def s1(): return readline().rstrip() def sl(): return [s for s in readline().split()] def sn(n): return [readline().rstrip() for i in range(n)] def sm(n): return (readline().rstrip() for i in range(n)) def redir(s): global readline;import os;fn=sys.argv[0] + f'/../in-{s}.txt';readline = open(fn).readline if os.path.exists(fn) else readline import os; if 'DEPTH' in os.environ: def printd(*a,**aa): # if (a and a[0]) == 'r': print(*a,**aa) else: def printd(*a,**aa): pass redir('c') n = i1() nodes = [[] for i in range(n+1)] depth = [0] * (n+1) notseen = [True] * (n+1) fa = [0] * (n+1) for i in range(1,n): u,v = nl() nodes[u].append(v) nodes[v].append(u) leaf = [len(nodes[i]) == 1 for i in range(n+1)] # leaf[1] = False leaf[1] = len(nodes[1]) < 1 # printd(leaf) stk = [(1,0,1)] # notseen[1] = False # notseen[1] = True ans = 0 # _ = 0 while stk: r, depth, weight = stk.pop() # _ += 1 # printd('-'*_,'top',r, depth, weight) if leaf[r]: ans += weight * depth continue ch = nodes[r] weight /= len(ch) - (r != 1) for c in ch: if notseen[c]: notseen[c] = False stk.append((c, depth+1, weight)) # printd(nodes) print(ans)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
n=int(input()) a=[[] for i in range(n+1)] for i in range(n-1): c,d,=map(int,input().split()) a[c].append(d) a[d].append(c) vis=[True]*(n+1) vis[1]=False r=[0]*(n+1);r[1]=1 q=[[1,1]] while len(q)!=0: x=q.pop() for i in a[x[0]]: if vis[i]: if x[0]==1: r[i]=r[x[0]]/(len(a[x[0]])) else: r[i]=r[x[0]]/(len(a[x[0]])-1) vis[i]=False q.append([i,r[i]]) an=0 for i in range(2,n+1): an+=r[i] print(an)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<long long> edge[100005]; long long vis[100005]; double dfs(long long n) { vis[n] = 1; long long cnt = 0; double path = 0; for (long long i = 0; i < edge[n].size(); i++) { if (vis[edge[n][i]] == 0) { path += dfs(edge[n][i]); cnt++; } } if (cnt == 0) return 0; return path / cnt + 1; } void solve() { long long n; cin >> n; for (long long i = 0; i < n - 1; i++) { long long x, y; cin >> x >> y; edge[x].push_back(y); edge[y].push_back(x); } cout << fixed << setprecision(10) << dfs(1); } int main() { long long tt = 1; while (tt--) { solve(); cout << endl; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { List<Integer>[] graph; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); graph = new List[n + 1]; for (int i = 0; i < n + 1; ++i) graph[i] = new ArrayList<>(); for (int i = 0; i < n - 1; ++i) { int u = in.nextInt(); int v = in.nextInt(); graph[u].add(v); graph[v].add(u); } out.printf("%.15f", dfs(1, -1, graph[1].size())); } double dfs(int root, int prev, int currentSize) { double res = 0; if (prev > -1) currentSize = graph[root].size() - 1; if (currentSize == 0) return 0; for (int child : graph[root]) { if (child == prev) continue; res += 1 + dfs(child, root, 0); } return res / currentSize; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
""" Author : raj1307 - Raj Singh Institute : Jalpaiguri Government Engineering College Date : 11.05.19 """ from __future__ import division, print_function import itertools,os,sys """ from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip else: from builtins import str as __str__ str = lambda x=b'': x if type(x) is bytes else __str__(x).encode() BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._buffer = BytesIO() self._fd = file.fileno() self._writable = 'x' in file.mode or 'r' not in file.mode self.write = self._buffer.write if self._writable else None def read(self): return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size) def readline(self): while self.newlines == 0: b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell() self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr) self.newlines += b.count(b'\n') + (not b) self.newlines -= 1 return self._buffer.readline() def flush(self): if self._writable: os.write(self._fd, self._buffer.getvalue()) self._buffer.truncate(0), self._buffer.seek(0) sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) input = lambda: sys.stdin.readline().rstrip(b'\r\n') def print(*args, **kwargs): sep, file = kwargs.pop('sep', b' '), kwargs.pop('file', sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop('end', b'\n')) if kwargs.pop('flush', False): file.flush() """ def ii(): return int(input()) def si(): return str(input()) def mi():return map(int,input().strip().split(" ")) def li():return list(mi()) from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace #from math import ceil,floor,log,sqrt,factorial,pow,pi #from bisect import bisect_left,bisect_right #from decimal import *, import threading def dmain(): sys.setrecursionlimit(100000000) threading.stack_size(40960000) thread = threading.Thread(target=main) thread.start() abc='abcdefghijklmnopqrstuvwxyz' abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25} mod=1000000007 dx,dy=[-1,1,0,0],[0,0,1,-1] def getKey(item): return item[0] def sort2(l):return sorted(l, key=getKey) def d2(n,m,num):return [[num for x in range(m)] for y in range(n)] def isPowerOfTwo (x): return (x and (not(x & (x - 1))) ) def decimalToBinary(n): return bin(n).replace("0b","") def ntl(n):return [int(i) for i in str(n)] def powerMod(x,y,p): res = 1 x %= p while y > 0: if y&1: res = (res*x)%p y = y>>1 x = (x*x)%p1 return res def gcd(x, y): while y: x, y = y, x % y return x # For getting input from input.txt file #sys.stdin = open('input.txt', 'r') # Printing the Output to output.txt file #sys.stdout = open('output.txt', 'w') graph=defaultdict(list) def dfs(v,prev): sum=0 cnt=0 for i in graph[v]: if i!=prev: sum+=dfs(i,v)+1 cnt+=1 if cnt: sum/=cnt return sum def main(): n=ii() for i in range(n-1): x,y=mi() graph[x].append(y) graph[y].append(x) s=dfs(1,0) print(s) if __name__ == "__main__": #main() dmain()
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import sys,threading def dfs(v,d,par=0): sum=0 for i in d[v]: if(i==par): continue sum+=dfs(i,d,v)+1 if(sum): return sum/(len(d[v])-(par!=0)) return 0.0 def main(): I=lambda:list(map(int,input().split())) n=I()[0] d={i:[] for i in range(1,n+1)} for i in range(n-1): u,v=I() d[u].append(v) d[v].append(u) print("%.10f"%dfs(1,d)) if __name__=='__main__': sys.setrecursionlimit(10**6) threading.stack_size(10**8) t = threading.Thread(target=main) t.start() t.join()
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import sys;readline = sys.stdin.readline def i1(): return int(readline()) def nl(): return [int(s) for s in readline().split()] # def nn(n): return [int(readline()) for i in range(n)] # def nnp(n,x): return [int(readline())+x for i in range(n)] # def nmp(n,x): return (int(readline())+x for i in range(n)) # def nlp(x): return [int(s)+x for s in readline().split()] # def nll(n): return [[int(s) for s in readline().split()] for i in range(n)] # def mll(n): return ([int(s) for s in readline().split()] for i in range(n)) # def s1(): return readline().rstrip() # def sl(): return [s for s in readline().split()] # def sn(n): return [readline().rstrip() for i in range(n)] # def sm(n): return (readline().rstrip() for i in range(n)) # def redir(s): global readline;import os;fn=sys.argv[0] + f'/../in-{s}.txt';readline = open(fn).readline if os.path.exists(fn) else readline # import os; # if 'DEPTH' in os.environ: # def printd(*a,**aa): # # if (a and a[0]) == 'r': # print(*a,**aa) # else: # def printd(*a,**aa): # pass # redir('c') n = i1() nodes = [[] for i in range(n+1)] depth = [0] * (n+1) notseen = [True] * (n+1) fa = [0] * (n+1) for i in range(1,n): u,v = nl() nodes[u].append(v) nodes[v].append(u) leaf = [len(nodes[i]) == 1 for i in range(n+1)] # leaf[1] = False leaf[1] = len(nodes[1]) < 1 # printd(leaf) stk = [(1,0,1)] # notseen[1] = False # notseen[1] = True ans = 0 # _ = 0 while stk: r, depth, weight = stk.pop() # _ += 1 # printd('-'*_,'top',r, depth, weight) if leaf[r]: ans += weight * depth continue ch = nodes[r] weight /= len(ch) - (r != 1) for c in ch: if notseen[c]: notseen[c] = False stk.append((c, depth+1, weight)) # printd(nodes) print(ans)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<int> v[(int)1e5 + 1]; vector<int> visited; vector<double> level, prob; void dfs(int u = 0) { visited[u] = 1; for (auto c : v[u]) if (!visited[c] and u == 0) { level[c] = level[u] + 1; prob[c] = prob[u] * (1.0 / v[u].size()); dfs(c); } else if (!visited[c]) { level[c] = level[u] + 1; prob[c] = prob[u] * (1.0 / (v[u].size() - 1)); dfs(c); } } int main() { int n; cin >> n; if (n == 1) { cout << 0 << '\n'; return 0; } level.resize(n, 0); visited.resize(n, 0); prob.resize(n, 1); for (int i = 0; i < n - 1; i++) { int x, y; cin >> x >> y; x--, y--; v[x].push_back(y); v[y].push_back(x); } dfs(); double ans = 0; for (int i = 1; i < n; i++) if (v[i].size() == 1) ans += level[i] * prob[i]; cout << fixed << setprecision(12) << ans << '\n'; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import javax.print.DocFlavor; import java.io.*; import java.util.*; public class Main { static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; static final int[][] STEPS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; boolean checkIndex(int index, int size) { return (0 <= index && index < size); } int abs(int a) { return Math.abs(a); } List<Integer>[] g; double[] ran; long[] depth; // ====================================================== void solve() throws IOException { int n = readInt(); g = new List[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<Integer>(); } for (int i = 0; i < n - 1; i++) { int f = readInt() - 1; int t = readInt() - 1; g[f].add(t); g[t].add(f); } used = new boolean[n]; ran = new double[n]; depth = new long[n]; ran[0] = 1; l = new ArrayList<Integer>(); dfs(0); double answer = 0; for (int i : l) { answer += ran[i] * depth[i]; } out.println(answer); } ArrayList<Integer> l; boolean[] used; void dfs(int from) { used[from] = true; for (int i : g[from]) { if (!used[i]) { int ver = g[from].size() - 1; if (from == 0) ver++; ran[i] = ran[from] / ver; depth[i] = depth[from] + 1; dfs(i); if (g[i].size() == 1) { l.add(i); } } } } int minInt(int... values) { int min = Integer.MAX_VALUE; for (int value : values) { min = Math.min(min, value); } return min; } int maxInt(int... values) { int max = Integer.MIN_VALUE; for (int value : values) { max = Math.max(max, value); } return max; } long minLong(long... values) { long min = Long.MAX_VALUE; for (long value : values) { min = Math.min(min, value); } return min; } long maxLong(long... values) { long max = Long.MIN_VALUE; for (long value : values) { max = Math.max(max, value); } return max; } public static void main(String[] args) { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer tok; void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } tok = new StringTokenizer(""); } void run() { try { long timeStart = System.currentTimeMillis(); init(); solve(); out.close(); long timeEnd = System.currentTimeMillis(); System.err.println("time = " + (timeEnd - timeStart) + " compiled"); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } String readLine() throws IOException { return in.readLine(); } String delimiter = " "; String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(delimiter); } int[] readIntArray(int b) { int a[] = new int[b]; for (int i = 0; i < b; i++) { try { a[i] = readInt(); } catch (IOException e) { e.printStackTrace(); } } return a; } long[] readLongArray(int b) { long a[] = new long[b]; for (int i = 0; i < b; i++) { try { a[i] = readLong(); } catch (IOException e) { e.printStackTrace(); } } return a; } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } void sortArrayInt(int[] a) { Integer arr[] = new Integer[a.length]; for (int i = 0; i < a.length; i++) { arr[i] = a[i]; } Arrays.sort(arr); for (int i = 0; i < a.length; i++) { a[i] = arr[i]; } } void sortArrayLong(long[] a) { Long arr[] = new Long[a.length]; for (int i = 0; i < a.length; i++) { arr[i] = a[i]; } Arrays.sort(arr); for (int i = 0; i < a.length; i++) { a[i] = arr[i]; } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int const MAXN = 2e6 + 9; long double dp[MAXN]; vector<vector<int>> g; void dfs(int node, int par) { bool cond = true; for (auto child : g[node]) { if (child == par) continue; cond = false; dfs(child, node); dp[node] += dp[child] / (long double)((int)g[node].size() - (node != 1)); } if (!cond) { dp[node]++; } } int main() { ios_base::sync_with_stdio(0), cin.tie(0); int n; cin >> n; g.resize(n + 1); if (n == 0) { cout << 0 << '\n'; return 0; } for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } dfs(1, 1); cout << setprecision(10) << dp[1] << '\n'; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const long long N = 1e6 + 5; vector<long long> graph[N]; double dfs(int u = 1, int par = 0) { double sum = 0.0; int childs = 0; for (auto &v : graph[u]) { if (v == par) continue; childs++; sum += dfs(v, u); } if (childs == 0) return 0; else return ((double)((1.0 * sum) / childs) + 1); } int32_t main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ; int n; cin >> n; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; graph[u].push_back(v); graph[v].push_back(u); } cout << fixed << setprecision(15) << dfs() << endl; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class c{ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[600]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } /* Added by me. */ public String readWord() throws IOException { byte[] buf = new byte[600]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (Character.isWhitespace(c)) //care ADD ANY WHITESPACE CHAR?? break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } //static class Reader public static void main(String[] args) throws IOException{ Reader s = new Reader(); //Init a reader! int n = s.nextInt(); ArrayList[] adj = new ArrayList[n+1]; for(int i = 1; i < n+1; i++) adj[i] = new ArrayList<Integer>(); for(int i = 1; i < n; i++){ int a = s.nextInt(); int b = s.nextInt(); adj[a].add((b)); adj[b].add((a)); } int root = 1; int[] dist = new int[n+1]; boolean[] vis = new boolean[n+1]; //bfs Deque<Integer> q = new LinkedList<Integer>(); q.addLast(root); vis[root] = true; dist[root] = 0; double[] pp = new double[n+1]; for(int r=0; r<=n; r++) pp[r] = (double) 1; double cp=1; double exp =0.0000000; boolean deb = false; while(q.peekFirst()!=null){ int p = q.peekFirst(); q.removeFirst(); double nChild=0; Iterator itr = adj[p].iterator(); while(itr.hasNext()){ int c =((Integer) itr.next()); if(!vis[c]) nChild++; } double prob=0; if(nChild==(double)0) {exp+=(dist[p] * pp[p]); if(deb) System.out.println(">>>@leaf: "+p);} else { prob = (double)1/nChild;} itr = adj[p].iterator(); while(itr.hasNext()){ int c = ((Integer)itr.next()); if(!vis[c]){ pp[c]*=(prob*pp[p]); dist[c] = dist[p] + 1; vis[c] = true; q.addLast(c); } } } System.out.printf("%.15f%n", exp); } //main } //public class Contest
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.awt.geom.*; import java.io.*; import java.math.*; public class Main { static ArrayList<Integer>[] v; static boolean[] visited; static ArrayList<Integer> dist; public static void main(String[] args) throws Exception { long startTime = System.nanoTime(); int n = in.nextInt(); v = new ArrayList[n + 2]; visited = new boolean[n + 2]; dist = new ArrayList<Integer>(); for (int i = 0; i < n + 2; i++) { v[i] = new ArrayList<>(); } for (int i = 1; i < n; i++) { int a = in.nextInt(); int b = in.nextInt(); v[a].add(b); v[b].add(a); } out.printf("%.15f\n", dfs(1)); long endTime = System.nanoTime(); err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms"); exit(0); } static double dfs(int vertex) { visited[vertex] = true; double count = 0; double ans = 0; for (int vv : v[vertex]) { if (!visited[vv]) { count++; ans += dfs(vv) + 1; } } if (count == 0) { return 0; } return ans / count; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static void exit(int a) { out.close(); err.close(); System.exit(a); } static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static OutputStream errStream = System.err; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); static PrintWriter err = new PrintWriter(errStream); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; unsigned long long modpow(long long x, long long n, long long m) { if (n == 0) return 1UL % m; unsigned long long u = modpow(x, n / 2, m); u = (u * u) % m; if (n % 2 == 1) u = (u * x) % m; return u; } bool prm[(int)1e3 + 5]; void make_prm() { prm[0] = prm[1] = true; for (int first = 2; first <= 1000; first++) { if (!prm[first]) { for (int second = 2 * first; second <= 1000; second += first) prm[second] = true; } } } vector<int> fac; void make_fac(int n) { for (int i = 1; i * i <= n; i++) { if (n % i == 0) { fac.push_back(i); fac.push_back(n / i); if (i * i == n) fac.pop_back(); } } } int n; vector<int> adj[100005]; vector<double> ans; void dfs(int, int, int, double, bool); int main() { cin >> n; for (long long i = (1); i <= (n - 1); i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } dfs(1, 0, -1, 1.0, false); double cnt = 0; for (auto u : ans) cnt += u; printf("%.20f", cnt); return 0; } int child(int n) { if (n == 1) return adj[n].size(); return adj[n].size() - 1; } void dfs(int n, int cnt, int parent, double prob, bool is) { if (adj[n].size() == 1 && is) { ans.push_back(cnt * prob); return; } if (n == 1) is = true; prob /= child(n); for (auto u : adj[n]) { if (u != parent) dfs(u, cnt + 1, n, prob, is); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; long double dfs(map<long long, vector<long long> >& m, vector<long long>& vis, long long sv) { vis[sv] = true; long double exp = 0; for (auto i : m[sv]) { if (!vis[i]) { exp += 1 + dfs(m, vis, i); } } if (exp == 0) return 0; if (sv == 1) return exp / (1.0 * m[sv].size()); return exp / (1.0 * (m[sv].size() - 1)); } int32_t main() { long long n; cin >> n; map<long long, vector<long long> > m; vector<long long> vis(n + 1); for (long long i = 0; i < n - 1; i++) { long long u, v; cin >> u >> v; m[u].push_back(v); m[v].push_back(u); } cout << fixed << setprecision(15) << dfs(m, vis, 1); }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; public class Main{ static ArrayList<Integer>[] arr; // static double[] arr1; public static double dfs(int a,int b){ double as = 0; for (int u : arr[a]){ if (u!=b){ double s = dfs(u,a); as = as+s+1; } } if (as==0){ return 0; } else{ return (b==-1)?(as/(double)arr[a].size()):(as/(double)(arr[a].size()-1)); // return as/(double)arr[a].size(); } } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); arr = new ArrayList[n]; // arr1 = new double[n]; for (int i=0;i<n;i++){ arr[i] = new ArrayList<Integer>(); } for (int i=0;i<n-1;i++){ int x = scan.nextInt()-1; int y = scan.nextInt()-1; arr[x].add(y); arr[y].add(x); } double qw = dfs(0,-1); System.out.println(qw); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; const long long mod = 1e9 + 7; struct node { int s, e, next; } edge[maxn]; int head[maxn], len; void add(int s, int e) { edge[len].e = e; edge[len].next = head[s]; head[s] = len++; } void init() { memset(head, -1, sizeof(head)); len = 0; } double dp[maxn]; void dfs(int x, int fa) { dp[x] = 0; int ans = 0; for (int i = head[x]; i != -1; i = edge[i].next) { int y = edge[i].e; if (y == fa) continue; dfs(y, x); dp[x] += dp[y]; ans++; } if (ans == 0) dp[x] = 0; else dp[x] = dp[x] / ans + 1; } int main() { int n; while (scanf("%d", &n) != EOF) { init(); int x, y; for (int i = 1; i < n; i++) { scanf("%d%d", &x, &y); add(x, y); add(y, x); } dfs(1, -1); printf("%.8f\n", dp[1]); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> const int MOD = 1e9 + 7; const int MAXN = 1e9 + 1; const double PI = 3.14159265359; using namespace std; vector<int> v[100001]; bool used[100001]; double dfs(int u) { used[u] = 1; double z = 0; int cnt = 0; for (int i = 0; i < v[u].size(); ++i) { int q = v[u][i]; if (!used[q]) { z += dfs(q) + 1; ++cnt; } } if (cnt) { z /= cnt; } return z; } int main() { int n, a, b; cin >> n; for (int i = 0; i < n - 1; ++i) { cin >> a >> b; v[a].push_back(b); v[b].push_back(a); } cout << fixed; cout << setprecision(15) << dfs(1); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<vector<int>> gph(100005); bool vis[100005]; double DFS(int sv) { vis[sv] = true; double tdis = 0; int chd = 0; for (long long int i = 0; i < gph[sv].size(); ++i) { if (!vis[gph[sv][i]]) { tdis += DFS(gph[sv][i]) + 1; chd++; } } if (chd) tdis /= chd; return tdis; } int main() { int t = 1; while (t--) { int n; cin >> n; for (long long int i = 0; i < n - 1; ++i) { int x, y; cin >> x >> y; gph[x].push_back(y); gph[y].push_back(x); } for (long long int i = 0; i < n + 1; ++i) vis[i] = false; double ans = DFS(1); printf("%0.6f", ans); } return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int n, ans, x, y; vector<int> a[200000]; double dfs(int v, int p) { int d = a[v].size(); if (p != -1) d--; double ret = 1.0; for (int i = 0; i < a[v].size(); i++) if (p != a[v][i]) { ret += dfs(a[v][i], v) * 1.0 / d; } return ret; } int main() { scanf("%d", &n); for (int i = 0; i < n - 1; i++) { scanf("%d %d", &x, &y); a[x].push_back(y); a[y].push_back(x); } printf("%.12lf", dfs(1, -1) - 1); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int N = 100000 + 5; vector<int> g[N]; double dfs(int x, int p) { double ans = 0; for (int next : g[x]) { if (next == p) continue; double r = 1 + dfs(next, x); ans += r / (g[x].size() - (p != 0)); } return ans; } int main() { ios_base::sync_with_stdio(false), cin.tie(0); int n; cin >> n; for (int i = 1, u, v; i < n; i++) cin >> u >> v, g[u].push_back(v), g[v].push_back(u); cout << fixed << setprecision(10) << dfs(1, 0) << "\n"; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.math.*; import java.io.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class Hello { static ArrayList<Integer> []nb = new ArrayList[200001]; static int n; static int []vis = new int[100001]; static double ans = 0; static void dfs(int r, double p) { ans += p; vis[r] = 1; for (int j = 0;j < nb[r].size();++j) { int nxt = nb[r].get(j).intValue(); if (vis[nxt] == 0) { if (r == 1) { dfs(nxt, p / nb[r].size()); } else { dfs(nxt, p / (nb[r].size() - 1)); } } } } public static void main(String[] args) { //Scanner in = new Scanner(System.in); FastReader in = new FastReader(System.in); n = in.nextInt(); for (int i = 1;i <= n;i++) { nb[i] = new ArrayList<Integer>(); } for (int i = 0;i < n - 1;i++) { int u = in.nextInt(); int v = in.nextInt(); nb[u].add(v); nb[v].add(u); } dfs(1, 1.0); System.out.println(ans -1 ); } } class FastReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c == ',') { c = read(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String nextLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String nextLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return nextLine(); } else { return readLine0(); } } public BigInteger nextBigInteger() { try { return new BigInteger(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pranay2516 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CJourney solver = new CJourney(); solver.solve(1, in, out); out.close(); } static class CJourney { ArrayList<Integer>[] a; public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); a = new ArrayList[n]; for (int i = 0; i < n; ++i) { a[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; ++i) { int u = in.nextInt() - 1, v = in.nextInt() - 1; a[u].add(v); a[v].add(u); } out.printf("%.10f", dfs(0, -1)); } double dfs(int v, int p) { double sum = 0; for (Integer u : a[v]) { if (u != p) { sum += dfs(u, v) + 1; } } return sum == 0 ? 0 : sum / (a[v].size() - (p != -1 ? 1 : 0)); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int N = (int)1e5 + 11; int n, x, y; vector<int> g[N]; long long cc; double ans, d[N], a[N]; void dfs(int v, int p = 0, int cur = 0, double dd = 1) { d[v] = dd; if (g[v].size() == 1 && p != 0) { ++cc; a[cur] += d[v]; } int c = 0; for (auto i : g[v]) if (i != p) ++c; for (auto i : g[v]) if (i != p) dfs(i, v, cur + 1, dd * ((1 + .0) / c)); } int main() { cin >> n; for (int i = 1; i < n; i++) { cin >> x >> y; g[x].push_back(y); g[y].push_back(x); } dfs(1); for (long long i = 1; i <= n; i++) if (a[i] > 0) ans += (i * a[i] + .0); printf("%.12f", ans); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<int> v[100010]; double res = 0.0; void dfs(int x, int p, double r, double pr) { if (v[x].size() == 1 && p != 0) { res += (pr * r); return; } double n = (double)v[x].size(); if (p != 0) n--; pr = pr / n; for (int y : v[x]) { if (y == p) continue; dfs(y, x, r + 1, pr); } } int main() { int n, x, y; cin >> n; for (int i = 1; i < n; i++) { cin >> x >> y; v[x].push_back(y); v[y].push_back(x); } dfs(1, 0, 0.0, 1.0); cout << setprecision(10) << fixed; cout << res; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.lang.reflect.Array; import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class main implements Runnable { static ArrayList<Integer> adj[]; static void Check2(int n) { adj = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } } static void add(int i, int j) { adj[i].add(j); adj[j].add(i); } public static void main(String[] args) { new Thread(null, new main(), "Check2", 1 << 26).start();// to increse stack size in java } static long mod = (long) (1e9 + 7); public void run() { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ //Scanner in=new Scanner(System.in); InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n=in.nextInt(); Check2(n); for(int i=0;i<n-1;i++){ int c=in.nextInt(); int d=in.nextInt(); add(c,d); } int v[]=new int[n+1]; p=new double[n+1]; x=new double[n+1]; dfs(1,v,0,-1,1); double ans=0; double deno=0; for(int i=1;i<=n;i++){ deno+=p[i]; } if(deno>0){ for(int i=1;i<=n;i++){ // w.println(x[i]+" "+p[i]); ans=ans+x[i]*p[i]; } w.printf("%.15f",ans); } else{ w.printf("%.15f",(double)0); } w.close(); } static int ans=0; static int co=0; static double p[]; static double x[]; static int dfs(int i,int v[],int cost,int par,double prob){ if(v[i]==1){ return 0; } v[i]=1; int flag=0; double q=adj[i].size(); if(par!=-1)q--; double val=(double)1/(double)q; // System.out.println(i+" "+prob+" "+val); for(Integer ne:adj[i]){ dfs(ne,v,cost+1,i,prob*val); flag++; } if(flag==1&&adj[i].get(0)==par){ x[i]+=cost; p[i]+=prob; } return 1; } static class pair { int a,b,c; pair(int x,int y){ a=x; b=y; } } static long power(long x,long y){ if(y==0)return 1%mod; if(y==1)return x%mod; long res=1; x=x%mod; while(y>0){ if((y%2)!=0){ res=(res*x)%mod; } y=y/2; x=(x*x)%mod; } return res; } static int gcd(int a,int b){ if(b==0)return a; return gcd(b,a%b); } static void sev(int a[],int n){ for(int i=2;i<=n;i++)a[i]=i; for(int i=2;i<=n;i++){ if(a[i]!=0){ for(int j=2*i;j<=n;){ a[j]=0; j=j+i; } } } } static class node{ int y; int val; node(int a,int b){ y=a; val=b; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #this is for recurssion questions from threading import stack_size,Thread sys.setrecursionlimit(10**6) stack_size(2**25) visited={} dic={} subsize={} def dfs(node): visited[node]=1 curr_size=0 count=0 for i in dic[node]: if visited[i]==0: count+=1 curr_size+=dfs(i) subsize[node]=curr_size/max(1,count) return (curr_size/max(1,count))+1 def main(): for _ in range(1): global dic,visited,subsize n=int(input()) if n==1: print(0) else: for i in range(n-1): u,v=map(int,input().split()) if u in dic: dic[u].append(v) else: dic[u]=[v] if v in dic: dic[v].append(u) else: dic[v]=[u] for i in range(1,n+1): visited[i]=0 subsize[i]=0 dfs(1) print(subsize[1]) Thread(target=main).start()
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.*; import java.util.*; public class Main { private static int[] used; private static double sum = 0; private static ArrayList<ArrayList<Integer>> list = new ArrayList<>(); public static void main(String[] args) throws IOException { BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); //bi = new BufferedReader(new InputStreamReader(new FileInputStream("src\\com\\company\\gryadka.txt"))); String str = bi.readLine(); StringTokenizer strtk = new StringTokenizer(str, " "); int n = (Integer.parseInt(strtk.nextToken())); int a, b; used = new int[n]; for (int i = 0; i < n; i++) list.add(new ArrayList<>()); for (int i = 0; i < n - 1; i++) { str = bi.readLine(); strtk = new StringTokenizer(str, " "); a = (Integer.parseInt(strtk.nextToken())); b = (Integer.parseInt(strtk.nextToken())); list.get(a - 1).add(b - 1); list.get(b - 1).add(a - 1); } dfs(1, 0, 0, -1); System.out.println(sum); } private static void dfs(double expect, int s, int start, int pr) { boolean end = true; used[start] = 1; double div = list.get(start).size() - 1; if (start == 0) div++; for (int i = 0; i < list.get(start).size(); ++i) { if (used[start] != 2) { if ((list.get(start).get(i) != pr)) { dfs(expect / div, s + 1, list.get(start).get(i), start); end = false; } } } used[start] = 2; if (end) { //System.out.println(s + " s " + (start + 1) + " start+1 " + expect); sum += expect * s; } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int mv = int(1e5) + 100, me = 2 * mv; int ant[me], to[me], d[mv], adj[mv], z; inline void add(int a, int b) { ant[z] = adj[a], to[z] = b, d[a]++, adj[a] = z++; swap(a, b); ant[z] = adj[a], to[z] = b, d[a]++, adj[a] = z++; } double dfs(int u = 0, int p = 0) { int deg = d[u] - 1 + (u == 0); double prob = 1.0 / deg, ans = 0; for (int i = adj[u]; i > -1; i = ant[i]) { int v = to[i]; if (v == p) continue; ans += prob * (1 + dfs(v, u)); } return ans; } int main() { ios::sync_with_stdio(0); memset(adj, -1, sizeof adj); int n; cin >> n; for (int i = 1, __ = n; i < __; ++i) { int a, b; cin >> a >> b; --a, --b; add(a, b); } cout << fixed << setprecision(10) << dfs() << endl; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.io.*; public class Journey{ public static List<List<Integer>> adj; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); adj = new ArrayList<>(); for(int i = 0; i < n; ++i) adj.add(new ArrayList<>()); for(int i = 0; i < n - 1; ++i) { int x = sc.nextInt(); int y = sc.nextInt(); adj.get(x - 1).add(y - 1); adj.get(y - 1).add(x - 1); } System.out.println(dfs(0, -1)); } public static double dfs(int x, int p) { //System.out.println("x " + x); double fc = 0; double count = 0; List<Integer> curr = adj.get(x); //System.out.println(curr); for(Integer y : curr) { //System.out.println("x " + x + " y " + y); if(y != p) { fc = fc + dfs(y, x); count++; } } //System.out.println(fc + " " + count); if(count == 0) return 0; return 1.0 + (fc/count); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<int> vec[100005]; int judge[100005]; double dfs(int x) { judge[x] = 1; double sum = 0; int all = 0; for (int a = 0; a < vec[x].size(); a++) { if (!judge[vec[x][a]]) all++; } if (all == 0) return 0; double temp = 1.0 / all; for (int a = 0; a < vec[x].size(); a++) { int tt = vec[x][a]; if (!judge[tt]) { sum += temp * (1 + dfs(tt)); } } return sum; } int main() { int n; while (scanf("%d", &n) != EOF) { for (int a = 1; a <= n; a++) vec[a].clear(); for (int a = 1; a < n; a++) { int x, y; scanf("%d%d", &x, &y); vec[x].push_back(y); vec[y].push_back(x); } memset(judge, 0, sizeof(judge)); printf("%.15f\n", dfs(1)); } return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
n=int(input()) graph=[] for i in range(n): graph.append([]) for _ in range(n-1): u,v=map(int,input().split()) graph[u-1].append(v-1) graph[v-1].append(u-1) ans=0 visited=[0]*n stack=[(0,1)] while stack: curr,prob=stack.pop() visited[curr]=1 ans+=prob r=[] for i in graph[curr]: if not visited[i]: r.append(i) if r: newprob=prob/len(r) for i in r: stack.append((i,newprob)) print(ans-1)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<vector<int> > g(100010); vector<long double> l(100010), e(100010); long double ans = 0; int k = 0; void dfs(int v, int p = -1) { for (int i = 0; i < g[v].size(); ++i) { if (g[v][i] == p) continue; if (v != 1) { e[g[v][i]] = e[v] / (g[v].size() - 1); } else { e[g[v][i]] = e[v] / g[v].size(); } l[g[v][i]] = l[v] + 1; dfs(g[v][i], v); } } int main() { ios_base::sync_with_stdio(0); int n; cin >> n; if (n == 1) { cout << 0; return 0; } l[1] = 0; e[1] = 1; for (int i = 0; i < n - 1; i++) { int x, y; cin >> x >> y; g[x].push_back(y); g[y].push_back(x); } dfs(1); for (int i = 1; i <= n; i++) if (i != 1 && g[i].size() == 1) { ans += e[i] * l[i]; k++; } cout << setprecision(10) << fixed << ans; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 1; vector<int> V[N]; long long prob[N]; int n, a, b, lvl[N], In[N]; double rez; void Dfs(int x) { In[x] = 1; if (V[x].size() == 1) rez += (double)lvl[x] / prob[x]; for (int i = 0; i < V[x].size(); i++) { if (!In[V[x][i]]) { lvl[V[x][i]] = lvl[x] + 1; long long z = (long long)V[x].size() - (long long)1; if (x == 1) z++; prob[V[x][i]] = prob[x] * z; if (prob[V[x][i]] > 0) Dfs(V[x][i]); } } } int main() { prob[1] = 1; scanf("%d", &n); for (int i = 1; i < n; i++) { scanf("%d %d", &a, &b); V[a].push_back(b); V[b].push_back(a); } Dfs(1); printf("%.8lf", rez); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by skull_crusher on 22/08/17. */ public class Journey { static Integer MXN = (int)1e5 + 9; static Integer N; static double dp[] = new double[MXN]; static ArrayList<ArrayList<Integer>> g; static void dfs(int cur, int par){ int child = 0; for(Integer u : g.get(cur)){ if(u == par) continue; dfs(u,cur); dp[cur] += dp[u]; child++; } if(child == 0) return; dp[cur] /= child; dp[cur] += 1; } static void Solve() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); g = new ArrayList<ArrayList<Integer>>(); for(int i = 1;i <= N;++i){ g.add(new ArrayList<Integer>()); } for(int i = 0;i < N - 1;++i){ StringTokenizer tk = new StringTokenizer(br.readLine()); Integer u = Integer.parseInt(tk.nextToken()); Integer v = Integer.parseInt(tk.nextToken()); u = u - 1; v = v - 1; g.get(u).add(v); g.get(v).add(u); } dfs(0,-1); System.out.println(dp[0]); } public static void main(String[] args) throws IOException { Solve(); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Scanner; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Yuan Lei */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { private List<Integer> edges[]; public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); edges = new ArrayList[n + 1]; for (int i = 1; i < n + 1; ++i) edges[i] = new ArrayList<>(); for (int i = 0; i < n - 1; ++i) { int x, y; x = in.nextInt(); y = in.nextInt(); edges[y].add(x); edges[x].add(y); } out.format("%.10f\n", dfs(1, 0)); } private double dfs(int node, int p) { double total = 0.0; int cnt = 0; for (int next : edges[node]) { if (next != p) { ++cnt; total += 1.0 + dfs(next, node); } } if (cnt > 0) return total / cnt; else return total; } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
from collections import deque def edge_input(m): edges=[] for i in range(m): edges.append(list(map(int,input().split()))) return edges def convert(edges): l={i:[] for i in range(1,n+1)} for i in edges: c1,c2=i[0],i[1] l[c1].append(c2) l[c2].append(c1) return l n=int(input()) l=convert(edge_input(n-1)) v={i:False for i in l} d={i:-1 for i in l} p={i:1 for i in l} end=deque([]) def bfs(x): d[x]=0 q=deque([x]) v[x]=True while len(q)!=0: temp=q.popleft() c=0 for i in l[temp]: if v[i]: continue d[i]=d[temp]+1 c+=1 q.append(i) if c==0: end.append(temp) else: for i in l[temp]: if v[i]: continue v[i]=True p[i]=p[temp]*(1/c) return d d=bfs(1) ans=0 #print(d) #print(end) #print(p) for i in end: ans+=p[i]*d[i] print(ans)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> g[n]; for (int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; --u; --v; g[u].push_back(v); g[v].push_back(u); } double ans = 0; function<void(int, int, int, double)> dfs; dfs = [&](int u, int pre, int l, double p) { int sz = g[u].size(); if (u) { --sz; } if (!sz) { ans += (double)l * p; return; } for (auto v : g[u]) { if (v != pre) { dfs(v, u, l + 1, p / double(sz)); } } }; dfs(0, 0, 0, 1); cout << fixed << setprecision(15) << ans << '\n'; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { private static final List<Integer>[] graph = (List<Integer>[]) new List[100_001]; private static final boolean[] used = new boolean[100_001]; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); for (int i = 0 ; i < n ; ++i) graph[i] = new ArrayList<>(); for (int i = 0 ; i < n - 1 ; ++i) { int from = scanner.nextInt() - 1; int to = scanner.nextInt() - 1; graph[from].add(to); graph[to].add(from); } System.out.println(dfs(0)); } private static double dfs(int v) { used[v] = true; double answer = 0; int counter = 0; for (int to : graph[v]) { if (!used[to]) { answer += dfs(to) + 1; counter++; } } if (counter == 0) return 0; return answer / counter; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
from functools import reduce n = int(input()) paths = [] for _ in range(n): paths.append([]) for _ in range(n - 1): i, j = [int(k) - 1 for k in input().split()] paths[i].append(j) paths[j].append(i) stack = [(0, 0, 1)] visited = set() answer = 0 while stack: vertex, deep, branching = stack.pop() visited.add(vertex) unvisited_count = reduce(lambda acc, el: acc if el in visited else acc + 1, paths[vertex], 0) if unvisited_count == 0: answer += deep / branching continue for other_vertex in paths[vertex]: if other_vertex not in visited: stack.append((other_vertex, deep + 1, branching * unvisited_count)) print(answer)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
n=int(input()) graph=[[] for i in range(n+1)] for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) graph[v].append(u) l=[] visited=[0]*(n+1) s=[0]*(n+1) prob=1 stack=[(1,prob)] while len(stack): m=0 c,prob=stack.pop() for i in graph[c]: if visited[i]==0: m+=1 if visited[c]==0: visited[c]=1 f=0 for i in graph[c]: if visited[i]==1: s[c]=1+s[i] else: f=1 stack.append((i,prob/m)) if f==0: l.append(s[c]*prob) print(sum(l))
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import sys input = sys.stdin.readline from collections import deque def bfs(): q = deque([(0, 1)]) dist = [-1]*n dist[0] = 0 res = 0 while q: v, p = q.popleft() flag = True for nv in G[v]: if dist[nv]==-1: dist[nv] = dist[v]+1 if v==0: np = p*len(G[v]) else: np = p*(len(G[v])-1) q.append((nv, np)) flag = False if flag: res += dist[v]/p return res n = int(input()) G = [[] for _ in range(n)] for _ in range(n-1): u, v = map(int, input().split()) G[u-1].append(v-1) G[v-1].append(u-1) print(bfs())
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.awt.List; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Locale; import java.util.TimeZone; public class A { public static void main(String[] args) { Locale.setDefault(Locale.US); InputStream inputstream = System.in; OutputStream outputstream = System.out; FastReader in = new FastReader(inputstream); PrintWriter out = new PrintWriter(outputstream); TaskA solver = new TaskA(); //int testcase = in.ni(); for (int i = 0; i < 1; i++) solver.solve(i, in, out); out.close(); } } class Node{ ArrayList<Node> adj = new ArrayList<>(); boolean visit = false; double dfs(int dist){ visit = true; double ans = 0; int count = 0; for(Node next : adj){ if(!next.visit){ ans += next.dfs(dist+1); count++; } } return count == 0 ? dist : ans / count ; } } class TaskA { public void solve(int testnumber, FastReader in, PrintWriter out) { int n = in.ni(); Node G[] = new Node[n]; for(int i = 0;i<G.length;i++){ G[i] = new Node(); } for(int i = 1;i<n;i++){ int a = in.ni()-1; int b = in.ni()-1; G[a].adj.add(G[b]); G[b].adj.add(G[a]); } double res = G[0].dfs(0); out.println(res); } } class FastReader { public InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public FastReader() { } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String ns() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] iArr(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String next() { return ns(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; using VI = vector<int>; using VVI = vector<VI>; using VB = vector<bool>; using VVB = vector<VB>; using VD = vector<double>; using VVD = vector<VD>; using VS = vector<string>; using PII = pair<int, int>; using VPII = vector<PII>; using VL = vector<long long>; using VVL = vector<VL>; VVI adj; int n; VD bfs(int start) { VD prob(n, -1.0); VI dist(n, -1); queue<int> q; prob[start] = 1.0; dist[start] = 0; q.push(start); VD ret; while (q.empty() == false) { int here = q.front(); q.pop(); bool isLeaf = true; for (auto there : adj[here]) { if (prob[there] < 0.0) { isLeaf = false; dist[there] = dist[here] + 1; prob[there] = prob[here] / ((int)adj[here].size() - (here != 0)); q.push(there); } } if (isLeaf == true) ret.emplace_back(dist[here] * prob[here]); } return ret; } double solvebfs() { VD leaves = bfs(0); return accumulate(leaves.begin(), leaves.end(), 0.0); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.precision(10); cout << fixed; cin >> n; adj.resize(n); for (int i = 0; i < (int)n - 1; ++i) { int u, v; cin >> u >> v; --u, --v; adj[u].emplace_back(v); adj[v].emplace_back(u); } cout << solvebfs() << endl; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; vector<int> v[100005]; bool ok[100005]; double val[100005]; double sol; double p; int dist[100005]; void DFS(int Nod) { ok[Nod] = 1; for (int i = 0; i < v[Nod].size(); i++) { int Vecin = v[Nod][i]; if (!ok[Vecin]) { dist[Vecin] = dist[Nod]; dist[Vecin]++; if (Nod != 1) val[Vecin] = (double)1 / (v[Nod].size() - 1) * val[Nod]; if (Nod == 1) val[Vecin] = (double)1 / v[Nod].size() * val[Nod]; DFS(Vecin); } } if (v[Nod].size() == 1 && Nod != 1) { sol += val[Nod] * dist[Nod]; p += val[Nod]; } } int main() { int n, r = 0; cin >> n; for (int i = 1; i <= n - 1; i++) { int x, y; cin >> x >> y; v[x].push_back(y); v[y].push_back(x); } val[1] = 1; if (n == 1) cout << fixed << setprecision(16) << (double)0; else { DFS(1); cout << fixed << setprecision(16) << (double)sol / p; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
def solve(graph, root, numNodes): graph[0] = {root} graph[root].add(0) solution = [0 for node in range(numNodes+1)] for (child, parent) in dfs(graph, 0, 0, numNodes): solution[child] /= (len(graph[child])-1) or 1 solution[parent] += 1 + solution[child] return solution[root] def dfs(graph, root, rootParent, numNodes): visited = [False for _ in range(numNodes+1)] queue = [(root, rootParent)] while queue: node, parent = queue[-1] visited[node] = True numUnvisitedNeighbors = 0 for neighbor in graph[node]: if not visited[neighbor]: queue.append((neighbor, node)) numUnvisitedNeighbors += 1 if numUnvisitedNeighbors == 0: yield queue.pop() def inputTree(numNodes): tree = {1: set()} for _ in range(numNodes-1): u, v = map(int, input().split()) tree.setdefault(u, set()).add(v) tree.setdefault(v, set()).add(u) return tree if __name__ == '__main__': numNodes = int(input()) print(solve(inputTree(numNodes), 1, numNodes))
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } const int MAXN = 300005; struct Data { int l, lt[MAXN], nt[MAXN], x[MAXN]; void clear() { l = 0; memset(lt, 0, sizeof(lt)); } void addedge(int a, int b) { l++; nt[l] = lt[a]; lt[a] = l; x[l] = b; } } E; double f[MAXN]; int n, m, a[MAXN]; void dfs(int x, int fa) { f[x] = 0; int tot = 0; for (int i = E.lt[x]; i; i = E.nt[i]) { int j = E.x[i]; if (j != fa) { dfs(j, x); f[x] += f[j] + 1; tot++; } } if (tot) f[x] /= tot; } int main() { n = read(); E.clear(); for (int i = (1); i <= (n - 1); ++i) { int x = read(), y = read(); E.addedge(x, y); E.addedge(y, x); } dfs(1, 0); printf("%.10f\n", f[1]); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; public class Journey { static ArrayList<Integer>[] graph; static boolean[] visited; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); visited = new boolean[N]; graph = new ArrayList[N]; for(int i = 0; i < N; i++) { graph[i] = new ArrayList<>(); } for(int i = 1; i < N; i++) { int n1 = scanner.nextInt()-1; int n2 = scanner.nextInt()-1; graph[n1].add(n2); graph[n2].add(n1); } visited[0] = true; System.out.println((dfs(0)-1)); } public static double dfs(int node) { double sum = 0.0; int size = 0; for(int i : graph[node]) { if (visited[i]) {continue;} visited[i] = true; size++; sum+=dfs(i); } if (size>0) { sum /= size; } //travel to current node sum++; //System.out.println("returning " + sum + " from node " + node); return sum; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
def f(): n = int(input()) if n == 1: print(0) return road = {} visited = {} for i in range(n-1): u, v = input().split() if u in road: road[u].append(v) else: road[u] = [v] if v in road: road[v].append(u) else: road[v] = [u] visited[u] = False visited[v] = False prob = {} length = {} res = [] queue = [] for k in road['1']: prob[k] = 1.0 / len(road['1']) length[k] = 1 queue.append(k) visited['1'] = True while len(queue) > 0: cur = queue[0] del queue[0] dest = [] for k in road[cur]: if not visited[k]: dest.append(k) if len(dest) == 0: res.append((cur, prob[cur], length[cur])) continue for k in dest: prob[k] = prob[cur] / len(dest) length[k] = length[cur] + 1 queue.append(k) visited[cur] = True val = 0.0 for item in res: val += item[1] * item[2] print(val) f()
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.*; import java.util.*; public class Ishu { static Scanner scan = new Scanner(System.in); static List<Integer>[] graph = new ArrayList[1]; static boolean[] visited = new boolean[1]; static double[] ans = new double[1]; static int leaf = 0; static void dfs(int ver, int dis) { visited[ver-1] = true; int n = graph[ver-1].size(); double tot = 0; int c = 0; int i; for(i=0;i<n;++i) { int u = graph[ver-1].get(i); if(!visited[u-1]) { dfs(u,dis+1); tot += ans[u-1]; ++c; } } if(c == 0) ans[ver-1] = 0; else ans[ver-1] = tot / c + 1; } static void tc() { int n = scan.nextInt(); int i; graph = new ArrayList[n]; visited = new boolean[n]; ans = new double[n]; for(i=0;i<n;++i) graph[i] = new ArrayList<Integer>(); for(i=0;i<n-1;++i) { int u = scan.nextInt(); int v = scan.nextInt(); graph[u-1].add(v); graph[v-1].add(u); } dfs(1,0); System.out.println(ans[0]); } public static void main(String[] args) { int t = 1; //t = scan.nextInt(); while(t-- > 0) tc(); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; int n, m; vector<vector<int> > G; vector<bool> mark; double dfs(int u, int p = -1) { mark[u] = true; double res = 0; int cnt = 0; for (int i = 0; i < G[u].size(); ++i) { int v = G[u][i]; if (mark[v] || v == p) continue; cnt++; res += dfs(v, u); } return (cnt ? res / cnt + 1 : 0); } int main() { cin >> n; m = n - 1; G.resize(n + 1); mark.assign(n + 1, false); for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; G[u].push_back(v); G[v].push_back(u); } cout << setprecision(7) << fixed << dfs(1); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
def zip_sorted(a,b): # sorted by a a,b = zip(*sorted(zip(a,b))) # sorted by b sorted(zip(a, b), key=lambda x: x[1]) return a,b import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) S = lambda : list(map(str,input().split())) def solve(adj,visited,degree,root): q = [root] s = [0] p = [1] prob = [] prob1 = [] i = 0 visited[root] = 1 while i<len(q): cur = q[i] if degree[cur]==1 and cur!=root: prob.append(s[i]) prob1.append(p[i]) i+=1 continue count =0 for j in range(len(adj[cur])): if visited[adj[cur][j]]!=1: count+=1 for j in range(len(adj[cur])): if visited[adj[cur][j]]!=1: q.append(adj[cur][j]) s.append(s[i]+1) p.append(p[i]*(1/count)) visited[adj[cur][j]]=1 i+=1 return prob,prob1 n, = I() adj = [[] for j in range(n)] degree = [0]*n visited = [0]*n for i in range(n-1): a1,b1 = I() adj[a1-1].append(b1-1) adj[b1-1].append(a1-1) degree[a1-1]+=1 degree[b1-1]+=1 a,b = (solve(adj,visited,degree,0)) sum1= 0 for i in range(len(a)): sum1+=a[i]*b[i] print(sum1)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
/* / フフ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ム / )\⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀Y (⠀⠀| ( ͡° ͜ʖ ͡°)⠀⠀⠀ ⌒(⠀ ノ (⠀ ノ⌒ Y ⌒ヽ-く __/ | _⠀。ノ| ノ。 |/ (⠀ー '_人`ー ノ ⠀|\  ̄ _人'彡ノ ⠀ )\⠀⠀ 。⠀⠀ / ⠀⠀(\⠀ #⠀ / ⠀/⠀⠀⠀/ὣ========D- /⠀⠀⠀/⠀ \ \⠀⠀\ ( (⠀)⠀⠀⠀⠀ ) ).⠀) (⠀⠀)⠀⠀⠀⠀⠀( | / |⠀ /⠀⠀⠀⠀⠀⠀ | / [_] ⠀⠀⠀⠀⠀[___] */ //1:-segment tree (class segment_tree) //2:-Prime check (class Prime_check) //3:-greatest common divisor (class GFG) //4:-modulus class (class mod_) import java.util.*; import java.io.*; import java.math.BigInteger; import java.math.BigDecimal; public class srx2 { static class segment_tree { static int st[]; public static void cons(int a[]) { int x=(int)Math.ceil((Math.log(a.length)/Math.log(2))); int size=2*((int)(Math.pow(2,x)))-1; st=new int[size]; consut(a,0,a.length-1,0); } public static int consut(int a[],int ss,int se,int si) { if(ss==se) { st[si]=a[ss]; return st[si]; } int mid=(ss+se)/2; st[si]=consut(a,ss,mid,2*si+1)+consut(a,mid+1,se,2*si+2); return st[si]; } public static int getsum(int ss,int se,int qs,int qe,int si) { if(qs<=ss && qe>=se) return st[si]; if(qs>se || ss>qe) return 0; int mid=(ss+se)/2; return getsum(ss,mid,qs,qe,2*si+1)+getsum(mid+1,se,qs,qe,2*si+2); } public static void update(int ss,int se,int i,int diff,int si) { if(i<ss || i>se) return; st[si]+=diff; int mid=(ss+se)/2; if(ss!=se) { update(ss,mid,i,diff,2*si+1); update(mid+1,se,i,diff,2*si+2); } } } static class Prime_check { public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } } static class GFG { public static long gfg(long a,long b) { if(b==0) return a; else return gfg(b,a%b); } } static class mod_ { static long MOD=1000000007; public static long fast_exp(long x, long y) { long res = 1; x = x % MOD; while (y > 0) { if((y & 1)==1) res = (res * x) % MOD; y = y >> 1; x = (x * x) % MOD; } return res; } } static class obj { int a; int b; int c; public obj(int x,int y,int z) { a=x; b=y; c=z; } } public static void main(String args[])throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ArrayList<Integer> ar[]=new ArrayList[n]; for(int i=0;i<n;i++) { ar[i]=new ArrayList<Integer>(); } for(int i=0;i<n-1;i++) { int x=sc.nextInt(); int y=sc.nextInt(); ar[x-1].add(y-1); ar[y-1].add(x-1); } int vis[]=new int[n]; double x=dfs(ar,vis,0,0.0,1.0,0.0); System.out.printf("%.7f\n",x); } public static double dfs(ArrayList<Integer> ar[],int vis[],int i,double ans,double div,double xx) { vis[i]=1; ans+=1; int flag=0; int count=0; for(int j=0;j<ar[i].size();j++) if(vis[ar[i].get(j)]==0) count+=1; if(count!=0) div*=count; //System.out.println("count: "+count+" of "+i+" present div= "+div); for(int j=0;j<ar[i].size();j++) { if(vis[ar[i].get(j)]==0) { flag=1; xx=dfs(ar,vis,ar[i].get(j),ans,div,xx); //System.out.println(xx+" "+i); } } if(flag==0) return xx+(1/div)*(ans-1); return xx; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.io.*; public class A { static BufferedReader br; static PrintWriter pw; static int inf = (int) 1e9; static long mod = (long) 1e9 + 7; static ArrayList<Integer>[] graph; static int n; public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException { // br = new BufferedReader(new FileReader(new File("chief.in"))); // br = new BufferedReader(new InputStreamReader(System.in)); Scanner sc = new Scanner(System.in); pw = new PrintWriter(System.out); n = sc.nextInt(); graph = new ArrayList[n]; for (int i = 0; i < graph.length; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; graph[u].add(v); graph[v].add(u); } pw.println(dfs(0, -1, 0)); pw.flush(); pw.close(); } static long[][] dp; static int[] color, down, total; static double dfs(int u, int pa, int l) { double sum = 0; double prop = (1.0 / (graph[u].size()-1)); if (pa == -1) prop = (1.0 / graph[u].size()); for (int v : graph[u]) { if (v == pa) continue; sum += (prop) * dfs(v, u, l + 1); } if (sum == 0) return l; return sum; } // // static void dfs2(int u, int pa, int costOFEdge) { // if (pa == -1) // total[u] = down[u]; // else // total[u] = costOFEdge == 0 ? total[pa] + 1 : total[pa] - 1; // // for (pair v : graph[u]) { // if (v.x == pa) // continue; // dfs2(v.x, u, v.y); // } // } // static long[] f, g; // // static void numOfSubtrees(int u, int pa) { // f[u] = 1; // for (int v : graph[u]) { // if (v == pa) // continue; // numOfSubtrees(v, u); // f[u] *= (1 + f[v]); // g[u] += f[v] + g[v]; // } // } static ArrayList<Integer> primes; // generated by sieve /* * 1. Generating a list of prime factors of N */ static ArrayList<Long> primeFactors(Long N) // O(sqrt(N) / ln sqrt(N)) { ArrayList<Long> factors = new ArrayList<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { if (N % p == 0) factors.add((long) p); while (N % p == 0) { N /= p; } if (idx + 1 == primes.size()) break; p = primes.get(++idx); } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static int[] isComposite; static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); if (1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } static int m, k; static double[] memo; static ArrayList<Integer>[] adj; static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static double dis(int x, int y, int z, int w) { return Math.sqrt((x - z) * (x - z) + (y - w) * (y - w)); } static int[] nxtarr() throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); int[] a = new int[st.countTokens()]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(st.nextToken()); } return a; } static long[] nxtarrLong() throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); long[] a = new long[st.countTokens()]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(st.nextToken()); } return a; } static class pair implements Comparable<pair> { int x; int y; public pair(int d, int u) { x = d; y = u; } @Override public int compareTo(pair o) { // TODO Auto-generated method stub if (y == o.y) return x - o.x; return y - o.y; } } static class triple implements Comparable<triple> { int x; int y; int z; public triple(int a, int b, int c) { x = a; y = b; z = c; } @Override public int compareTo(triple o) { // TODO Auto-generated method stub return x - o.x; } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
from collections import deque def bfs(graph): visited = len(graph) * [False] visited[0] = True q = deque([(0, 0, 1.)]) res = 0. while len(q) > 0: root, depth, prob = q.popleft() if len(graph[root]) == 1 and visited[graph[root][0]]: res += prob * depth else: num_child = 0 for child in graph[root]: if not visited[child]: num_child += 1 for child in graph[root]: if not visited[child]: visited[child] = True q.append((child, depth + 1, prob * 1. / num_child)) return res n = int(raw_input()) graph = [[] for _ in range(n)] for _ in range(n-1): node1, node2 = map(int, raw_input().split(' ')) node1 -= 1 node2 -= 1 graph[node1].append(node2) graph[node2].append(node1) if n == 1: print 0. else: print bfs(graph)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; double ans = 0.0; int n; bool vis[100005]; void bfs(vector<int> vec[], int src, int lvl) { queue<pair<int, pair<int, double> > > qu; qu.push(make_pair(src, make_pair(0, 1.0))); vis[src] = true; int i; while (!qu.empty()) { pair<int, pair<int, double> > top = qu.front(); qu.pop(); bool flg = false; int cnt = 0; for (i = 0; i < vec[top.first].size(); i++) { if (!vis[vec[top.first][i]]) { cnt++; } } for (i = 0; i < vec[top.first].size(); i++) { if (!vis[vec[top.first][i]]) { flg = true; qu.push(make_pair(vec[top.first][i], make_pair(top.second.first + 1, top.second.second * (1.0 / (cnt * 1.0))))); vis[vec[top.first][i]] = true; } } if (flg == false) ans += (double)(top.second.first) * (double)(top.second.second * 1.0); } } int main() { cin >> n; int i; vector<int> vec[100005]; for (i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; vec[u].push_back(v); vec[v].push_back(u); } bfs(vec, 1, 0); long long int sum = 0; printf("%lf", ans); }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 7, INF = 0x3f3f3f3f, mz = 1e9 + 7; const double PI = acos(0.0) * 2; template <typename T1> T1 gcd(T1 a, T1 b) { return b ? gcd(b, a % b) : a; } vector<int> m[N]; bool vis[N]; double dfs(int u, double p) { int cnt = 0; vis[u] = 1; for (int i = 0; i < m[u].size(); i++) { if (vis[m[u][i]]) continue; cnt++; } double ans = 0.0, q = 1.0 / max(cnt, 1); for (int i = 0; i < m[u].size(); i++) { if (vis[m[u][i]]) continue; ans += p * q + dfs(m[u][i], p * q); } return ans; } int main() { int n, u, v; scanf("%d", &n); for (int i = 1; i < n; i++) { scanf("%d%d", &u, &v); m[u].push_back(v); m[v].push_back(u); } printf("%.7f\n", dfs(1, 1.0)); return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.ArrayList; import java.util.Scanner; public class Programm { private static ArrayList<Integer>[] list = new ArrayList[(100000 + 1)]; private static double dfs(int node, int parent) { double sum = 0; for (int i : list[node]) { if (i != parent) { sum += (1 + dfs(i, node)); } } if (sum == 0) return 0; return (parent == 0) ? (sum / (double) list[node].size()) : (sum / (double) (list[node].size() - 1)); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); for (int i = 0; i <= n; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < (n - 1); i++) { int a = scan.nextInt(); int b = scan.nextInt(); list[a].add(b); list[b].add(a); } System.out.printf("%.6f", dfs(1, 0)); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
class Node: def __init__(self, index): self.neighbours = [] self.index = index self.prob = 1.0 self.vis = False self.length = 0 def addNode(self, city): self.neighbours.append(city) if self.index == 1: self.prob = 1.0 / len(self.neighbours) else: l = len(self.neighbours) self.prob = 1.0 if l < 2 else (1.0 / (l - 1)) n = int(input()) if n == 1: print(0) exit() cities = {} for i in range(n-1): a, b = map( lambda k: int(k), input().split()) #print ("test ", a, " to ", b) if a not in cities: cities[a] = Node(a) cities[a].addNode(b) if b not in cities: cities[b] = Node(b) cities[b].addNode(a) if len(cities) == 2: print(1) exit() # for i in range(1, n + 1, 1): # print ("city.index ", cities[i].index, ' roads ', cities[i].neighbours, ' prob ', cities[i].prob) # deadends = [] # deadendsProb = [] # def Parse(city, prob, length, oldCity): # #print ('parse ', city.index) # newprob = 1.0 if oldCity == 0 else cities[oldCity].prob # #print ('nnewProb ', newprob) # prob *= newprob # #print (city.index, ' len ', len(city.neighbours)) # if len(city.neighbours) == 1 and oldCity != 0: # deadends.append(length) # deadendsProb.append(prob) # else: # #print (city.neighbours) # length += 1 # for c in city.neighbours: # if c != oldCity: # Parse(cities[c], prob, length, city.index ) # Parse(cities[1], 1.0, 0, 0) # #for i in range(len(deadends)): # # print('len ', deadends[i], ' prob ', deadendsProb[i]) # ans = sum(map(lambda l, p: l * p, deadends, deadendsProb)) # #print('ans', ans) # print(ans) def inorder(city): s = [] s.append(city) #print ('index ', city.index) #print ('neighbours ', city.neighbours) while s: city = s.pop() city.vis = True if city.neighbours: if city.index == 1 or len(city.neighbours) > 1: for c in city.neighbours: if not cities[c].vis: cities[c].length = city.length + 1 cities[c].prob *= city.prob s.append(cities[c]) else: yield (city.index, city.prob, city.length) test = sum([city[1] * city[2] for city in inorder(cities[1])]) print(test) # this is a tree
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...); } vector<int> G[100010]; int n; bool visited[100010]; double dfs(int l) { visited[l] = 1; if (G[l].size() == 0) return 0; int num = 0; double sum = 0.0; for (int i = 0; i < int(G[l].size()); i++) { if (!visited[G[l][i]]) { num++; sum += 1 + dfs(G[l][i]); } } if (num == 0) return 0; sum = sum * 1.0 / num; return sum; } int main() { memset(visited, 0, sizeof(visited)); int x, y; cin >> n; for (int i = 0; i < n - 1; i++) { cin >> x >> y; x--; y--; G[x].push_back(y); G[y].push_back(x); } double ans = dfs(0); cout << setprecision(8) << fixed << ans << endl; return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.*; import java.util.*; public class Solution { static ArrayList<Integer> adj[]; static boolean visited[]; static int N; public static void main(String ag[]) { Scanner sc=new Scanner(System.in); int i,j,k; N=sc.nextInt(); if(N==1) { System.out.println(0.0); return; } visited=new boolean[N+1]; adj=new ArrayList[N+1]; for(i=0;i<=N;i++) adj[i]=new ArrayList<>(); for(i=1;i<N;i++) { int a=sc.nextInt(); int b=sc.nextInt(); adj[a].add(b); adj[b].add(a); } System.out.println(DFS(1,1.0,0)); } public static double DFS(int node,double prob,int height) { visited[node]=true; Iterator<Integer> itr=adj[node].iterator(); double total=0.0; while(itr.hasNext()) { int next=itr.next(); if(!visited[next]) { total+=DFS(next,prob,height+1); } } if(adj[node].size()==1&&node!=1) return height*1.0; return node==1?(total/adj[node].size()):(total/(adj[node].size()-1)); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; const int maxn = 100010; int n; double ans; struct E { int v, nxt; } e[2 * maxn]; int cnt, h[maxn]; void init() { cnt = 0; memset(h, -1, sizeof(h)); } void add(int u, int v) { e[cnt].v = v; e[cnt].nxt = h[u]; h[u] = cnt++; } void dfs(int pos, int pre, double len, double sum) { int all = 0; for (int k = h[pos]; ~k; k = e[k].nxt) { int v = e[k].v; if (v == pre) continue; all++; } if (all == 0) { ans += len * sum; return; } for (int k = h[pos]; ~k; k = e[k].nxt) { int v = e[k].v; if (v == pre) continue; dfs(v, pos, len + 1, sum / all); } } int main() { while (scanf("%d", &n) != EOF) { int u, v; ans = 0; init(); for (int i = 1; i < n; i++) { scanf("%d%d", &u, &v); add(u, v); add(v, u); } dfs(1, 0, 0, 1.0); printf("%.10lf\n", ans); } return 0; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.lang.*; import java.io.*; import java.io.PrintWriter; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader in = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static int N = 100000+10; static ArrayList<ArrayList<Integer>> cities = new ArrayList<>(); public static double dfs(int vertex,int parent){ double ans = 0; for(int i=0;i<cities.get(vertex).size();i++){ if(cities.get(vertex).get(i)!=parent){ ans+=dfs(cities.get(vertex).get(i),vertex); ans++; } } if(ans==0){ return 0; }else{ if(parent==-1){ return ans/cities.get(vertex).size(); }else{ return ans/(cities.get(vertex).size()-1); } } } public static void solve(){ int n; int u,v; n = in.nextInt(); for(int i=0;i<n;i++){ cities.add(new ArrayList<Integer>()); } for(int i=0;i<n-1;i++){ u = in.nextInt(); v = in.nextInt(); cities.get(u-1).add(v-1); cities.get(v-1).add(u-1); } out.println(dfs(0,-1)); out.flush(); return; } public static void main(String[] args) { int T=1; // T = s.nextInt(); while(T>0){ // System.out.println("TEST CASE: "+T); solve(); T--; } } } class Pair{ int first; int second; Pair(int a,int b){ this.first = a; this.second = b; } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class A { static ArrayList<Integer> []adj; static boolean []visited; static double []ans; public static void dfs(int u) { visited[u]=true; int c=0; double x=0; for(int v:adj[u]) if(!visited[v]) { dfs(v); c++; x+=ans[v]; } ans[u]=c==0?0:x/c+1; } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); adj=new ArrayList [n]; for(int i=0;i<n;i++) adj[i]=new ArrayList(); for(int i=0;i<n-1;i++) { int u=sc.nextInt()-1,v=sc.nextInt()-1; adj[u].add(v); adj[v].add(u); } visited=new boolean[n]; ans=new double[n]; dfs(0); System.out.println(ans[0]); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br=new BufferedReader(new InputStreamReader(s)); } public String nextLine() throws IOException { return br.readLine(); } public String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
from collections import defaultdict from decimal import * n = int(input()) adj = defaultdict(list) for i in range(n-1): u, v = map(int, input().split()) adj[u].append(v) adj[v].append(u) v = [0]*(n+1) q = [(1, 1, 0)] ans = 0 while q: e, prob, d = q.pop() v[e] = 1 cmps = 0 for cmp in adj[e]: if not v[cmp]: cmps += 1 if cmps == 0: ans += prob*d else: for cmp in adj[e]: if not v[cmp]: q.append((cmp, prob/cmps, d+1)) print(ans)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization("unroll-loops") const long long max_sz = 1e5 + 1; const long long mod = 1e9 + 7; const long long MAXN = 4e18 + 1; const int N = 500023; char flip(char k) { if (k == '0') return '1'; return '0'; } long long sum_digit(long long n) { long long a = 0, i; for (i = n; i > 0; i = i / 10) { a += (i % 10); } return a; } long long gcd(long long a, long long b) { if (b == 0) return a; return gcd(b, a % b); } bool isPowerOfTwo(int n) { if (n == 0) return false; return (ceil(log2(n)) == floor(log2(n))); } long long expo(long long a, long long b, long long m); vector<bool> vis; vector<vector<long long> > g; void ipgraph(long long m) { long long u, v; while (m--) { cin >> u >> v; u--, v--; g[u].push_back(v); g[v].push_back(u); } } long double jhc = 0.0; void dfs(long long i, long long lvl, long double p) { vis[i] = true; if (i != 0 && g[i].size() != 1) p *= 1.0 / (g[i].size() - 1); else if (i == 0) p *= 1.0 / (g[i].size()); else p = p; for (auto j : g[i]) { if (!vis[j]) { dfs(j, lvl + 1, p); } } if (g[i].size() == 1 && i != 0) { jhc += p * lvl; } } void solve() { long long i, j, n, m, k; cin >> n; vis.assign(n, false); g.assign(n, {}); ipgraph(n - 1); dfs(0, 0, 1); printf("%.15Lf", jhc); } int main() { long long t = 1; while (t--) { solve(); } return 0; } long long expo(long long a, long long b, long long m) { if (b == 0) return 1; long long p = expo(a, b / 2, m) % m; p = (p * p) % m; return (b % 2 == 0) ? p : (a * p) % m; }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.io.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { ArrayList<ArrayList<Integer>> arr; public void solve() throws Exception { // int t=sc.nextInt(); // for(int ii=1;ii<=t;ii++) // { //System.out.print("Case #"+ii+": "); int n=sc.nextInt(); if(n==1) { System.out.println(0); return; } arr=new ArrayList<>(n); for(int i=0;i<n;i++) { arr.add(new ArrayList<>()); } for(int i=0;i<n-1;i++) { int u=sc.nextInt(); int v=sc.nextInt(); u--; v--; arr.get(u).add(v); arr.get(v).add(u); } System.out.println(dfs(0,0)); } public double dfs(int u,int p) { if(u!=0 && arr.get(u).size()==1) return 0.0; double sum=0; for(int x : arr.get(u)) { if(x==p) continue; sum+=1+dfs(x,u); } if(u!=0) return (double)sum/(double)(arr.get(u).size()-1); else return (double)sum/(double)(arr.get(u).size()); } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); sc = new FastScanner(in); solve(); } catch (Throwable uncaught) { Solution.uncaught = uncaught; } finally { out.close(); } } public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); if (Solution.uncaught != null) { throw Solution.uncaught; } } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author /\ */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); CJourney solver = new CJourney(); solver.solve(1, in, out); out.close(); } static class CJourney { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; adj[u].add(v); adj[v].add(u); } int[] cnt = new int[n]; double[] prob = new double[n]; prob[0] = 1.0; boolean[] vis = new boolean[n]; vis[0] = true; dfs(adj, 0, cnt, vis, prob); double res = 0; for (int i = 1; i < n; i++) { if (adj[i].size() == 1) { res += prob[i] * cnt[i]; } } out.println(res); } void dfs(List<Integer>[] adj, int node, int[] cnt, boolean[] vis, double[] prob) { for (int i : adj[node]) { if (!vis[i]) { vis[i] = true; cnt[i] = cnt[node] + 1; prob[i] = prob[node] * 1.0 / (node == 0 ? adj[node].size() : adj[node].size() - 1); dfs(adj, i, cnt, vis, prob); } } } } static class Scanner { private StringTokenizer st; private BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
n=int(input()) g={i:[] for i in range(n)} for i in range(n-1): u,v=map(int,input().split()) u-=1 v-=1 g[u].append(v) g[v].append(u) v=set() q=[(0,1,0)] res=0 while q: s,p,l=q.pop() v.add(s) dep=0 for to in g[s]: if to not in v: dep+=1 if dep==0: res+=p*l else: for to in g[s]: if to not in v: q.append((to,p/dep,l+1)) print(res)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
import java.util.*; import java.io.*; public class test5 { static double answer; static List<List<Integer>> adj; public static void main(String[] args) throws Exception { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader f = new BufferedReader(new FileReader("test.in")); PrintWriter out = new PrintWriter(System.out); int N = Integer.parseInt(f.readLine()); adj = new ArrayList<>(N); adj.add(null); for (int i = 0; i < N; i++) { adj.add(new LinkedList<>()); } for (int i = 0; i < N - 1; i++) { StringTokenizer st = new StringTokenizer(f.readLine()); int u = Integer.parseInt(st.nextToken()); int v = Integer.parseInt(st.nextToken()); adj.get(u).add(v); adj.get(v).add(u); } dfs(1, 0, 1.0, 0); out.printf("%.7f", answer); out.close(); } static void dfs(int u, int par, double probability, int depth) { int children = adj.get(u).size(); if (u > 1) children--; for (int v : adj.get(u)) { if (v == par) continue; dfs(v, u, probability / children, depth + 1); } if (children == 0){ answer += probability * depth; } } }