1. 程式人生 > >【題解】CF#Bubble Cup X - Finals E-Casinos and travel

【題解】CF#Bubble Cup X - Finals E-Casinos and travel

std 解釋 ble con print sin cup getc str

  天啊我怎麽這麽蠢……寫了一個樹形dp,的確發現記錄的很多值並沒有什麽用,然而當時腦子沒轉過彎來還是寫了這個樹形dp……雖然能A但就不解釋了,總之是個垃圾算法(??д??)

#include <bits/stdc++.h>
using namespace std;
#define maxn 1000000
#define mod 1000000007
#define int long long
int n, ans, rec, fa[maxn];
int g[maxn][2], f[maxn][2];

int read()
{
    
int x = 0, k = 1; char c; c = getchar(); while(c < 0 || c > 9) { if(c == -) k = -1; c = getchar(); } while(c >= 0 && c <= 9) x = x * 10 + c - 0, c = getchar(); return x * k; } struct edge { int cnp, to[maxn], last[maxn], head[maxn]; edge() { cnp
= 2; } void add(int u, int v) { to[cnp] = v, last[cnp] = head[u], head[u] = cnp ++; to[cnp] = u, last[cnp] = head[v], head[v] = cnp ++; } }E1; void Up(int &x, int y) { x = (x + y) % mod; } int Inv(int x) { int base = 1, timer = mod - 2; for(; timer; timer >>= 1
, x = x * x % mod) if(timer & 1) base = base * x % mod; return base; } void dfs(int u) { int t1 = 1, flag = 0; for(int i = E1.head[u]; i; i = E1.last[i]) { int v = E1.to[i]; if(v == fa[u]) continue; fa[v] = u; dfs(v); flag = 1; t1 = t1 * ((g[v][0] + g[v][1]) % mod) % mod; } if(flag) g[u][0] = g[u][1] = t1 % mod; else g[u][0] = 1, g[u][1] = 0; } void dfs2(int u) { int t1 = f[fa[u]][0] * g[fa[u]][0] % mod * Inv(g[u][0] + g[u][1]) % mod; int t2 = f[fa[u]][1] * g[fa[u]][1] % mod * Inv(g[u][0] + g[u][1]) % mod; f[u][0] = f[u][1] = (t1 + t2) % mod; if(u == 1) f[u][0] = 1; if(u == 1 && rec != 1) f[u][1] = 1; Up(ans, (f[u][0] * g[u][0]) % mod * 2 % mod); for(int i = E1.head[u]; i; i = E1.last[i]) { int v = E1.to[i]; if(v == fa[u]) continue; dfs2(v); } } signed main() { n = read(); for(int i = 1; i < n; i ++) { int x = read(), y = read(); E1.add(x, y); if(x == 1 || y == 1) rec ++; } dfs(1); dfs2(1); printf("%I64d\n", ans); return 0; }

  其實我們可以直接推公式。我們註意到每個葉子結點完全可以決定從根到的路徑上的節點是偶數個還是奇數個,也就是它本身是否建造賭場是一定的。至於剩下的節點,我們大可以隨便決定。所以 \(ans = (n - x) * 2^{n - x} + x * 2 ^ {n - x + 1}\)。(其中 \(x\) 為葉子節點的個數)。那麽整理一下就是 \(ans = (n + x) * 2 ^ {n - x}\)。

【題解】CF#Bubble Cup X - Finals E-Casinos and travel