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.
import java.io.IOException; import java.io.InputStream; import java.util.*; public class C { static InputStream is; //String INPUT = ""; public static void main(String[] args) throws Exception { is = System.in; int n = ni(); ArrayList<Integer>[] aj = new ArrayList[n+1]; for (int i = 0; i < aj.length; i++) { aj[i] = new ArrayList<>(); } for(int i =0; i < n-1; i++){ int a = ni(); int b = ni(); aj[a].add(b); aj[b].add(a); } ArrayDeque<Integer> dq = new ArrayDeque<>(); dq.add(1); int[] dist = new int[n+1]; double[] p = new double[n+1]; Arrays.fill(dist, 987654321); dist[1] = 0; p[1] = 1; double ans = 0; while(!dq.isEmpty()){ int at = dq.poll(); int d = dist[at]; boolean nogo = true; int numc = 0; for(int to : aj[at]){ if(dist[to] > d+1){ numc++; } } for(int to : aj[at]){ if(dist[to] > d+1){ nogo = false; dist[to] = d+1; p[to] = p[at]/numc; dq.add(to); } } if(nogo){ ans += p[at]*dist[at]; } } System.out.println(ans); } private static byte[] inbuf = new byte[1024]; public static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double nd() { return Double.parseDouble(ns()); } private static char nc() { return (char)skip(); } private static String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private static int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private static int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } //private boolean oj = System.getProperty("ONLINE_JUDGE") != null; //private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
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]; long double ans = 0; void dfs(int at, int par, long double h = 0, long double p = 1) { for (__typeof(v[at].begin()) it = v[at].begin(); it != v[at].end(); it++) { int to = *it; if (to != par) { long double p1 = v[at].size(); if (at != 1) p1 -= 1.0; p1 = 1 / p1; dfs(to, at, h + 1, p * p1); } } if (at != 1) { if (v[at].size() == 1) { ans += p * h; } } } int main() { ios_base::sync_with_stdio(false); int n; cin >> n; for (int i = 1; i <= n - 1; i++) { int a, b; cin >> a >> b; v[a].push_back(b); v[b].push_back(a); } dfs(1, 0, 0); cout << fixed << setprecision(10) << 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; long double ans; vector<int> g[100005]; void dfs(int v, int p, int l, long double f) { if ((int)g[v].size() == 1 && g[v][0] == p) { ans += (long double)l * f; return; } int k = (int)g[v].size(); if (v != 1) --k; for (int i = 0; i < (int)g[v].size(); ++i) { int to = g[v][i]; if (to != p) dfs(to, v, l + 1, (long double)f / k); } } int main() { ios_base::sync_with_stdio(0); cin >> n; for (int i = 0; i < n - 1; ++i) { int from, to; cin >> from >> to; g[from].push_back(to); g[to].push_back(from); } dfs(1, 1, 0, 1); cout.precision(7); cout << 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.
import java.util.*; public class Main { @SuppressWarnings("unchecked") static LinkedList<Integer>[] G = new LinkedList[(int)(1e5+10)]; static double dfs (int u,int p){ double sum = 0; for(int i: G[u]){ if(i != p){ sum += (1+dfs(i,u)); } } if(sum == 0){ return 0; } return (p==0)?(sum/(double)G[u].size()):(sum/(double)(G[u].size()-1)); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N= sc.nextInt(); for(int i=0;i<=N;i++){ G[i] = new LinkedList<Integer>(); } for(int i=0;i<(N-1);i++){ int x = sc.nextInt(); int y = sc.nextInt(); G[x].add(y); G[y].add(x); } System.out.printf("%.9f",dfs(1,0)); sc.close(); } }
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.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class CF_428_DIV2_C { private static ArrayList<Integer>[] adjList; private static boolean[] visited; private static double dfs(int u) { if (adjList[u].size() == 0) return 0.0; if (adjList[u].size() == 1 && u != 0) return 0.0; double childrenExp = 0.0; visited[u] = true; for (int v : adjList[u]) { if (!visited[v]) { childrenExp += dfs(v); } } if (u == 0) return childrenExp/adjList[u].size() + 1.0; return childrenExp/(adjList[u].size() - 1) + 1.0; } public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); int n = Integer.parseInt(input.readLine()); adjList = new ArrayList[n]; visited = new boolean[n]; for (int i = 0; i < n; i++)adjList[i] = new ArrayList<>(); String[] line; int u, v; for (int i = 0; i < n - 1; i++) { line = input.readLine().split(" "); u = Integer.parseInt(line[0]) - 1; v = Integer.parseInt(line[1]) - 1; adjList[u].add(v); adjList[v].add(u); } System.out.println(dfs(0)); input.close(); } }
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.
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import deque def main(): n=int(input()) tree=[[] for _ in range(n+1)] for _ in range(n-1): x,y=map(int,input().split()) tree[x].append(y) tree[y].append(x) leaf=[] for i in range(1,n+1): if len(tree[i])==1 and i!=1: leaf.append(i) h=[0]*(n+1) pro=[0]*(n+1) v=[0]*(n+1) pro[0]=1 q=deque() q.append((0,1)) while q : p,c=q.popleft() h[c]=h[p]+1 pro[c]=pro[p]/(max(len(tree[p])-(p!=1),1)) v[c]=1 for i in tree[c]: if not v[i]: q.append((c,i)) ans=0 for i in leaf: ans+=(h[i]-1)*pro[i] print(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") 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 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) notseen = [0] * (n+1) fa = [0] * (n+1) for i in range(1,n): u,v = nl() nodes[u].append(v) nodes[v].append(u) stk = [1] # notseen[1] = False # notseen[1] = True notseen[1] = 1 depth[1] = 0 _ = 0 pathlens = [] while stk: r = stk[-1] ch = nodes[r] _ += 1 # printd('-'*_, r, ch) # printd(stk) if notseen[r] < 2: # if r == 1: # notseen[1] = False d = 1 + depth[r] for c in ch: if notseen[c] == 0: notseen[c] += 1 fa[c] = r depth[c] = d stk.append(c) notseen[r] += 1 # printd('-'*_,"stk", r, stk) else: r = stk.pop() ch = nodes[r] if len(ch) == 1 and r != 1: pathlens.append(depth[r]) else: total = sum(depth[i] for i in ch if i != fa[r]) deg = len(ch) - (r != 1) # printd("r",r,total,deg, [i for i in ch if i != fa[r]]) depth[r] = total/deg if deg else total # printd(nodes) # printd("depth", depth) # printd(pathlens) print(depth[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 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; int n, i, a, b; vector<int> adj[100005]; long double res = 0, sol[100004] = {}; long long int len = 0; long double prop[100005]; void goo(int ind, int fat) { if (adj[ind].size() == 1 - (fat == -1)) { sol[len] += prop[ind]; return; } for (int u = 0; u < adj[ind].size(); u++) { if (adj[ind][u] == fat) continue; len++; prop[adj[ind][u]] = prop[ind] / (adj[ind].size() - 1 * (fat != -1)); goo(adj[ind][u], ind); len--; } } int main() { prop[1] = 1; cin >> n; for (i = 0; i < n - 1; i++) { cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } goo(1, -1); for (i = 0; i < 100002; i++) res += i * sol[i]; cout << setprecision(10) << res << 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 sys def r(): return list(map(int, input().split())) n = int(input()) edge = [r() for i in range(n-1)] adj = [[] for i in range(n+1)] for e in edge: adj[e[0]].append(e[1]) adj[e[1]].append(e[0]) prob = [0.0 for i in range(n+1)] d = [0 for i in range(n+1)] visited = [False for i in range(n+1)] prob[1] = 1 ans = 0.0 st = [1] visited[1] = True while st: u = st.pop() cnt = len(adj[u]) if u != 1: cnt -= 1 if cnt == 0: ans = ans + prob[u]*d[u] else: for v in adj[u]: if not visited[v]: visited[v] = True prob[v] = prob[u]*(1.0/cnt) d[v] = d[u]+1 st.append(v) 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; using li = long long; using ld = long double; using pii = pair<int, int>; istream& operator>>(istream& cin, vector<int>& a) { for (int i = 0; i < a.size(); i++) cin >> a[i]; return cin; } ostream& operator<<(ostream& cout, vector<int>& a) { for (int i = 0; i < a.size(); i++) cout << a[i] << ' '; cout << endl; return cout; } const int M = 1e9 + 7; const int N = 1e5 + 13; vector<int> g[N]; ld dp[N]; void dfs(int v, int p) { dp[v] = 0; int cnt = 0; for (auto u : g[v]) if (u != p) { dfs(u, v); dp[v] += dp[u] + 1; cnt++; } if (g[v].size() > 1) dp[v] /= cnt; } void solve() { int n; cin >> n; for (int i = 0; i < n - 1; i++) { int v, u; cin >> v >> u; v--; u--; g[v].push_back(u); g[u].push_back(v); } dfs(0, -1); cout << setprecision(20) << fixed << dp[0] << endl; } int main() { int t = 1; while (t--) 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 sys from collections import deque read=lambda:sys.stdin.readline().rstrip() readi=lambda:int(sys.stdin.readline()) writeln=lambda x:sys.stdout.write(str(x)+"\n") write=lambda x:sys.stdout.write(x) N = readi() if N == 1: writeln(0) exit() G = [set() for _ in range(N)] for _ in range(N-1): u, v = map(int, read().split()) G[u-1].add(v-1) G[v-1].add(u-1) visited = [0]*N prev = [0]*N visited[0] = 1 prev[0] = 1 q = deque([0]) lengths = [] ev = 0 while q: cur = q.popleft() n_neighbor = len(G[cur]) if cur == 0: divs = n_neighbor else: divs = n_neighbor - 1 if n_neighbor == 1 and cur != 0: ev += (visited[cur] - 1)*prev[cur] continue for nxt in G[cur]: if not visited[nxt]: visited[nxt] = visited[cur] + 1 prev[nxt] = (1 / divs)*prev[cur] q.append(nxt) print('%.12f' % ev)
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) notseen = [0] * (n+1) fa = [0] * (n+1) for i in range(1,n): u,v = nl() nodes[u].append(v) nodes[v].append(u) stk = [1] # notseen[1] = False # notseen[1] = True notseen[1] = 1 depth[1] = 0 _ = 0 pathlens = [] while stk: r = stk[-1] ch = nodes[r] _ += 1 # printd('-'*_, r, ch) # printd(stk) if notseen[r] < 2: # if r == 1: # notseen[1] = False d = 1 + depth[r] for c in ch: if notseen[c] == 0: notseen[c] += 1 fa[c] = r depth[c] = d stk.append(c) notseen[r] += 1 # printd('-'*_,"stk", r, stk) else: r = stk.pop() ch = nodes[r] if len(ch) == 1 and r != 1: pathlens.append(depth[r]) else: total = sum(depth[i] for i in ch if i != fa[r]) deg = len(ch) - (r != 1) # printd("r",r,total,deg, [i for i in ch if i != fa[r]]) depth[r] = total/deg if deg else total # printd(nodes) # printd("depth", depth) # printd(pathlens) print(depth[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.io.*; import java.util.*; import java.lang.*; import java.util.HashMap; public class templ implements Runnable { class pair { int first,second; pair(int f,int s) { first=f; second=s; } } public static ArrayList<Integer> g[]=new ArrayList[1000000]; public static int vis[]=new int[1000000]; public static double p[]=new double[1000000]; public static int l[]=new int[1000000]; public static double ans=0; void dfs(int n,int par) { vis[n]=1; if(par!=-1) { l[n]=l[par]+1; if(par==1) p[n]=p[par]*(double)1/g[par].size(); else p[n]=p[par]*(double)1/(g[par].size()-1); } for(int i=0;i<g[n].size();i++) { int u=g[n].get(i); if(vis[u]==0) dfs(u,n); } } int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1; } void merge1(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i]<=R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort1(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort1(arr, l, m); sort1(arr , m+1, r); merge1(arr, l, m, r); } } void merge3(int arr[],int arr1[],int arr2[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; int L1[]=new int[n1]; int R1[]=new int[n2]; int L2[]=new int[n1]; int R2[]=new int[n2]; //long L3[]=new long[n1]; //long R3[]=new long[n2]; for (int i=0; i<n1; ++i) { L[i] = arr[l + i]; L1[i]=arr1[l+i]; L2[i]=arr2[l+i]; //L3[i]=arr3[l+i]; } for (int j=0; j<n2; ++j) { R[j] = arr[m + 1+ j]; R1[j]=arr1[m+1+j]; R2[j]=arr2[m+1+j]; //R3[j]=arr3[m+1+j]; } int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; //arr3[k]=L3[i]; i++; } else { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; //arr3[k]=R3[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; //arr3[k]=L3[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; //arr3[k]=R3[j]; j++; k++; } } void sort3(int arr[],int arr1[],int arr2[], int l, int r) { if (l < r) { int m = (l+r)/2; sort3(arr,arr1,arr2, l, m); sort3(arr ,arr1,arr2, m+1, r); merge3(arr,arr1,arr2,l, m, r); } } void merge2(int arr[],int arr1[],int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; int L1[]=new int[n1]; int R1[]=new int[n2]; for (int i=0; i<n1; ++i) { L[i] = arr[l + i]; L1[i]=arr1[l+i]; } for (int j=0; j<n2; ++j) { R[j] = arr[m + 1+ j]; R1[j]=arr1[m+1+j]; } int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; arr1[k]=L1[i]; i++; } else { arr[k] = R[j]; arr1[k]=R1[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; arr1[k]=L1[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; arr1[k]=R1[j]; j++; k++; } } void sort2(int arr[],int arr1[],int l, int r) { if (l < r) { int m = (l+r)/2; sort2(arr,arr1, l, m); sort2(arr ,arr1, m+1, r); merge2(arr,arr1,l, m, r); } } void merge4(int arr[],int arr1[],int arr2[],int arr3[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; int L1[]=new int[n1]; int R1[]=new int[n2]; int L2[]=new int[n1]; int R2[]=new int[n2]; int L3[]=new int[n1]; int R3[]=new int[n2]; for (int i=0; i<n1; ++i) { L[i] = arr[l + i]; L1[i]=arr1[l+i]; L2[i]=arr2[l+i]; L3[i]=arr3[l+i]; } for (int j=0; j<n2; ++j) { R[j] = arr[m + 1+ j]; R1[j]=arr1[m+1+j]; R2[j]=arr2[m+1+j]; R3[j]=arr3[m+1+j]; } int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; arr3[k]=L3[i]; i++; } else { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; arr3[k]=R3[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; arr3[k]=L3[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; arr3[k]=R3[j]; j++; k++; } } void sort4(int arr[],int arr1[],int arr2[],int arr3[], int l, int r) { if (l < r) { int m = (l+r)/2; sort4(arr,arr1,arr2,arr3, l, m); sort4(arr ,arr1,arr2,arr3, m+1, r); merge4(arr,arr1,arr2,arr3,l, m, r); } } public int justsmall(int a[],int l,int r,int x) { int p=-1; while(l<=r) { int mid=(l+r)/2; if(a[mid]<=x) { p=mid; l=mid+1; } else r=mid-1; } return p; } public int justlarge(int a[],int l,int r,int x) { int p=0; while(l<=r) { int mid=(l+r)/2; if(a[mid]<=x) { l=mid+1; } else { p=a[mid]; r = mid - 1; } } return p; } long gcd(long x,long y) { if(x%y==0) return y; else return(gcd(y,x%y)); } long fact(long n) { long ans=1; for(int i=1;i<=n;i++) ans*=i; return ans; } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<26).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); templ ob=new templ(); int n=in.ni(); for(int i=1;i<=n;i++) g[i]=new ArrayList(); for(int i=1;i<n;i++) { int u=in.ni(); int v=in.ni(); g[u].add(v); g[v].add(u); } for(int i=1;i<=n;i++) { p[i]=0; l[i]=-1; } l[1]=0; p[1]=1; ob.dfs(1,-1); for(int i=1;i<=n;i++) { if(g[i].size()==1) ans=ans+l[i]*p[i]; } System.out.printf("%.7f",ans); out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { 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 ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } 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] = ni(); } return a; } 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -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 = 1e5 + 9; int n, vis[maxn]; vector<int> adj[maxn]; double dfs(int v, int p) { vis[v] = 1; double ans = 0, num = 0; for (int u : adj[v]) { if (u != p) { ans += dfs(u, v); num += 1; } } return num ? ans / num + 1 : 0.0; } int main() { cin >> n; int a, b; for (int i = 0; i < n - 1; i++) { cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } cout << setprecision(8) << 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.
import java.util.*; public class CF839C { public static void main(String[]args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Point[] cities = new Point[n+1]; for(int i=1;i<=n;i++) cities[i] = new Point(i); for(int i=0;i<n-1;i++) { int a = sc.nextInt(); int b = sc.nextInt(); cities[a].adjacencies.add(cities[b]); cities[b].adjacencies.add(cities[a]); } System.out.println(recur(cities[1], 0)); } public static double recur(Point start, int previous) { int adj = start.adjacencies.size(); if(adj==1&&previous!=0) return 1.0; double ret; if(previous==0) ret=0.0; else ret=1.0; for(Point x:start.adjacencies) { if(x.CN==previous) continue; if(previous==0) ret+=(1.0/(adj))*recur(x, start.CN); else ret+=(1.0/(adj-1.0))*recur(x, start.CN); } return ret; } } class Point { public int CN; //city number public ArrayList<Point> adjacencies = new ArrayList<Point>(); public Point(int CN) { this.CN=CN; } public void Adjacent(Point other) { adjacencies.add(other); } }
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.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; import javax.management.relation.RelationServiceNotRegisteredException; public class hehehe { static int count=0; static int flag=0; static double eps=(double)1e-6; static long mod=(long)1e9+7; static int maxcount=0; static int index=0; static int fac[]=new int[10]; static int end_time[]=new int[100001]; static int bit[]=new int[100001]; static int vis_time[]=new int[100001]; static int flat_tree[]=new int[200001]; static ArrayList<ArrayList<Integer>> tree=new ArrayList<>(); static ArrayList<ArrayList<Integer>> table=new ArrayList<>(); static int traverser[]=new int[100001]; static int par[]=new int[100001]; static boolean vis[]=new boolean[100001]; static int tim = 0; //li, ri and index are stored in queries vector //in that order, as the sort function will use //the value li for comparison static ArrayList< pair1 > queries=new ArrayList<>(); //ans[i] stores answer to ith query static int ans[]=new int[100001]; static HashSet<String> hm; public static void main(String args[]){ InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); Scanner sc=new Scanner(System.in); //----------My Code---------- Queue<Pair> a=new LinkedList<Pair>(); int n=in.nextInt(); int visited[]=new int[n+1]; ArrayList<ArrayList<Integer>> arr=new ArrayList<>(); for(int i=0;i<=n;i++) arr.add(new ArrayList<Integer>()); for(int i=0;i<n-1;i++){ int x=in.nextInt(); int y=in.nextInt(); arr.get(x).add(y); arr.get(y).add(x); } int par[]=new int[n+1]; a.add(new Pair(1,1,0)); par[1]=0; double ans=0; while(!a.isEmpty()){ Pair p=a.poll(); int pop=p.x; if(visited[pop]==0){ int val=0; //System.out.println(arr.get(pop).size()); for(int i=0;i<arr.get(pop).size();i++){ int ele=arr.get(pop).get(i); if(visited[ele]==0) { par[ele]=pop; if(pop!=1) a.add(new Pair(ele,p.y*(((double)1/(arr.get(pop).size()-1))),p.z+1)); else a.add(new Pair(ele,p.y*(((double)1/(arr.get(pop).size()))),p.z+1)); } else val++; } if(val==arr.get(pop).size()){ ans+=p.y*p.z; //System.out.println(p.y+" "+p.z+""+pop); } } visited[pop]=1; } System.out.println(ans); //-- -------------The End----------------- - out.close(); } static int rec(String ans,int length){ if(length<=2){ return 0; } else{ int flag=0; char start=ans.charAt(0); for(int i=1;i<ans.length()-1;i++){ if(start=='0'&&ans.charAt(i+1)=='0'){ if(ans.charAt(i)=='0'){ flag=1; // System.out.println(ans.substring(0, i)+ans.substring(i+1)); count=count^rec(ans.substring(0, i)+ans.substring(i+1),ans.length()-1); } else if (ans.charAt(i)=='1'){ flag=1; // System.out.println(ans.substring(0, i)+ans.substring(i+1)); count=count^rec(ans.substring(0, i)+ans.substring(i+1),ans.length()-1); } } start=ans.charAt(i); } if(flag==0) return count^1; return count; } } static int recursiveBinarySearch(int[] sortedArray, int start, int end, int key) { while (start < end) { int mid = start + (end - start) / 2; if (key < sortedArray[mid]) { end=mid-1; } else if (key >=sortedArray[mid]) { start=mid+1; } } return (start); } static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } static long gcd(long x, long y) { if(x==0||y==0) return 0; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } static class Pair { int x; double y; int z; //int i; Pair(int xx,double yy,int zz){ x=xx; y=yy; //i=ii; z=zz; } } static class pair1 implements Comparable<pair1>{ Pair p; int x; pair1(Pair p,int x){ this.p=p; this.x=x; } public int compareTo(pair1 arg0) { return Integer.compare(p.x, arg0.p.x); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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()); } } }
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("unroll-loops") #pragma GCC optimize("Ofast") #pragma GCC optimize("O0") #pragma GCC optimize("O1") long long pw(int a, int b) { long long ret = 1; long long mul = a; while (b > 0) { if (b & 1) ret *= mul; mul *= mul; b /= 2; } return ret; } long long to_int(string s) { long long ret = 0; for (int(i) = (0); (i) < (s.size()); (i)++) { ret += pw(10, s.size() - i - 1) * (long long)(s[i] - '0'); } return ret; } const int MAXN = 1e5 + 15; vector<int> adj[MAXN]; long double ex[MAXN]; int n; void dfs(int v, int p) { for (int(i) = (0); (i) < (adj[v].size()); (i)++) { if (adj[v][i] != p) { dfs(adj[v][i], v); ex[v] += (ex[adj[v][i]] + 1) / (adj[v].size() - (v != 0)); } } } int main() { cin >> n; for (int(i) = (0); (i) < (n - 1); (i)++) { int s, e; cin >> s >> e; s--, e--; adj[s].push_back(e), adj[e].push_back(s); } dfs(0, 0); cout << fixed << setprecision(10) << ex[0] << "\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.
""" Author : Arif Ahmad Date : Algo : Difficulty : """ from sys import stdin, stdout def main(): n = int(stdin.readline().strip()) g = [[] for i in range(n+1)] for _ in range(n-1): u, v = [int(_) for _ in stdin.readline().strip().split()] g[u].append(v) g[v].append(u) visited = [False for i in range(n+1)] paths = [] # iterative DFS stack = [(1, 0, 1)] while len(stack): u, plen, prb = stack.pop() visited[u] = True nBranch = 0 for v in g[u]: if not visited[v]: nBranch += 1 if nBranch > 0: probability = prb * (1 / nBranch) for v in g[u]: if not visited[v]: stack.append((v, plen+1, probability)) if nBranch == 0: paths.append(plen * prb) ans = sum(paths) stdout.write(str(ans) + '\n') if __name__ == '__main__': main()