Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class DiameterOfRandomTree {
- int n;
- ArrayList<Integer>[] e;
- double[][][] prob;
- boolean[][][] done;
- double calc(int cur, int from, int mustLeq)
- {
- if(mustLeq < 0) return 0;
- if(done[cur][from][mustLeq]) return prob[cur][from][mustLeq];
- double p = 1.0;
- for(int i = 0; i < e[cur].size(); i++)
- {
- int t = e[cur].get(i);
- if(t == from) continue;
- double curProb = 0;
- curProb += 0.5 * calc(t, cur, mustLeq - 1);
- curProb += 0.5 * calc(t, cur, mustLeq - 2);
- p *= curProb;
- }
- done[cur][from][mustLeq] = true;
- prob[cur][from][mustLeq] = p;
- return p;
- }
- double exact(int cur, int from, int l)
- {
- return calc(cur, from, l) - calc(cur, from, l-1);
- }
- public double getExpectation(int[] a, int[] b)
- {
- n = a.length + 1;
- prob = new double[n][n][n+1];
- done = new boolean[n][n][n+1];
- e = new ArrayList[n];
- for(int i = 0; i < n; i++)
- e[i] = new ArrayList<Integer>();
- for(int i = 0; i < a.length; i++)
- {
- e[a[i]].add(b[i]);
- e[b[i]].add(a[i]);
- }
- double ans = 0;
- // center is at middle of edge
- for(int i = 0; i < a.length; i++)
- for(int x = 0; x < n; x ++)
- {
- ans += exact(a[i], b[i], x) * exact(b[i], a[i], x) * (2 * x + 1.5);
- ans += exact(a[i], b[i], x) * exact(b[i], a[i], x-1) * (2 * x + 1) * 0.5;
- ans += exact(a[i], b[i], x-1) * exact(b[i], a[i], x) * (2 * x + 1) * 0.5;
- }
- // center is at vertex
- for(int i = 0; i < n; i++)
- for(int x = 0; x < n; x++)
- {
- double p1 = 1.0;
- for(int j = 0; j < e[i].size(); j++)
- {
- double curP = 0;
- curP += 0.5 * calc(e[i].get(j), i, x - 1);
- curP += 0.5 * calc(e[i].get(j), i, x - 2);
- p1 *= curP;
- }
- double p2 = 1.0;
- for(int j = 0; j < e[i].size(); j++)
- {
- double curP = 0;
- curP += 0.5 * calc(e[i].get(j), i, x - 2);
- curP += 0.5 * calc(e[i].get(j), i, x - 3);
- p2 *= curP;
- }
- p1 -= p2;
- for(int s = 0; s < e[i].size(); s++)
- {
- double p3 = 1.0;
- for(int j = 0; j < e[i].size(); j++)
- {
- if(j != s)
- {
- double curP = 0;
- curP += 0.5 * calc(e[i].get(j), i, x - 2);
- curP += 0.5 * calc(e[i].get(j), i, x - 3);
- p3 *= curP;
- }
- else
- {
- double curP = 0;
- curP += 0.5 * exact(e[i].get(j), i, x - 1);
- curP += 0.5 * exact(e[i].get(j), i, x - 2);
- p3 *= curP;
- }
- }
- p1 -= p3;
- }
- ans += p1 * x * 2;
- }
- return ans;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement