4835: 遗忘之树

题意:点分治,选标号最小的重心,上一次重心向下一次重心连有向边,求原树方案数。


md我真不知道当初比赛时干什么去了...现在一眼秒啊...

\(size[v]=\frac{size[u]}{2}\)时原树只能向编号\(>u\)的点连边,\(O(nlogn)\)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 1e5+5, mo = 1e9+7;
inline int read() {
char c=getchar(); int x=0,f=1;
while(c<'0'||c>'9') {if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();}
return x*f;
} int n, m, u, v, ind[N], root;
struct edge {int v, ne;} e[N];
int cnt, h[N];
inline void ins(int u, int v) {
e[++cnt] = (edge) {v, h[u]}; h[u] = cnt;
} int size[N]; ll f[N];
int find(int u, int p) {
int ans = u > p;
for(int i=h[u]; i; i=e[i].ne) ans += find(e[i].v, p);
return ans;
}
void dp(int u) {
size[u] = 1; f[u] = 1;
for(int i=h[u]; i; i=e[i].ne) dp(e[i].v), size[u] += size[e[i].v];
int half = size[u] & 1 ? 0 : size[u] >> 1;
for(int i=h[u]; i; i=e[i].ne) {
int v = e[i].v;
if(size[v] == half) f[u] = f[u] * f[v] %mo * find(v, u) %mo;
else f[u] = f[u] * f[v] %mo * size[v] %mo;
}
}
int main() {
freopen("in", "r", stdin);
int T = read();
while(T--) {
n = read(); m = read();
cnt = 0; memset(h, 0, sizeof(h));
memset(f, 0, sizeof(f));
memset(ind, 0, sizeof(ind));
for(int i=1; i<=m; i++) u = read(), v = read(), ins(u, v), ind[v]++;
for(int i=1; i<=n; i++) if(!ind[i]) {root = i; break;}
dp(root);
printf("%lld\n", f[root]);
}
}
04-14 18:34