只有一周了QAQ
2.21
CF 629 E Famil Door and Roads
其实Tarjan的时候搞一搞,就O(n+m)了吖。
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 using namespace std; 5 typedef long long LL; 6 typedef pair<int, int> pii; 7 const int maxn = 1e5 + 10; 8 vector<pii> q[maxn]; 9 double ans[maxn]; 10 11 //Tree 12 int cnt, h[maxn]; 13 struct edge 14 { 15 int to, pre; 16 } e[maxn<<1]; 17 18 void add(int from, int to) 19 { 20 cnt++; 21 e[cnt].pre = h[from]; 22 e[cnt].to = to; 23 h[from] = cnt; 24 } 25 26 //TreeDP 27 LL dis[maxn], fdis[maxn]; 28 int sz[maxn], fsz[maxn], dep[maxn]; 29 void dfs1(int p, int d) 30 { 31 sz[p] = 1, dep[p] = d; 32 for(int i = h[p]; i; i = e[i].pre) 33 { 34 int to = e[i].to; 35 if(dep[to]) continue; 36 dfs1(to, d + 1); 37 sz[p] += sz[to]; 38 dis[p] += dis[to] + sz[to]; 39 } 40 } 41 42 //Tarjan 43 int fa[maxn], vis[maxn], cur[maxn]; 44 int Find(int x) 45 { 46 return fa[x] == x ? x : fa[x] = Find(fa[x]); 47 } 48 49 void dfs2(int p, int f) 50 { 51 fa[p] = p, vis[p] = 2; 52 if(p != 1) 53 { 54 fsz[p] = fsz[f] + sz[f] - sz[p]; 55 fdis[p] = fdis[f] + dis[f] - dis[p] - sz[p] + fsz[p]; 56 } 57 for(int i = h[p]; i; i = e[i].pre) 58 { 59 int to = e[i].to; 60 if(to == f) continue; 61 cur[p] = to; 62 dfs2(to, p); 63 fa[to] = p; 64 } 65 vis[p] = 1; 66 int qsz = q[p].size(); 67 for(int i = 0; i < qsz; i++) 68 { 69 int to = q[p][i].first, id = q[p][i].second; 70 if(!vis[to]) continue; 71 int anc = Find(to); 72 if(anc == to) 73 { 74 LL d = dep[p] - dep[to] + 1; 75 ans[id] = (1.0 * dis[p] * fsz[cur[to]] + 1.0 * (fdis[cur[to]] - (LL)fsz[cur[to]]) * sz[p]) / sz[p] / fsz[cur[to]] + d; 76 } 77 else if(vis[p] == 1 && anc != p) 78 { 79 LL d = dep[p] + dep[to] - dep[anc] - dep[anc] + 1; 80 ans[id] = (1.0 * dis[p] * sz[to] + 1.0 * dis[to] * sz[p]) / sz[p] / sz[to] + d; 81 } 82 } 83 return; 84 } 85 86 int main(void) 87 { 88 int n, m; 89 scanf("%d %d", &n, &m); 90 for(int i = 1; i < n; i++) 91 { 92 int u, v; 93 scanf("%d %d", &u, &v); 94 add(u, v), add(v, u); 95 } 96 for(int i = 0; i < m; i++) 97 { 98 int u, v; 99 scanf("%d %d", &u, &v); 100 q[u].push_back(pii(v, i)); 101 q[v].push_back(pii(u, i)); 102 } 103 dfs1(1, 1); 104 dfs2(1, 0); 105 for(int i = 0; i < m; i++) printf("%.9f\n", ans[i]); 106 return 0; 107 }
Aguin
时间: 2024-12-21 16:20:52