【HDU5647】DZY Loves Connecting【TreeDP】

【题目链接】

BC的一个题。

看的这篇文章。

/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#pragma comment(linker, "/STACK:102400000,102400000")

typedef unsigned long long ULL;
typedef unsigned int uint;

const int maxn = 200005;
const uint p = 1000000007;

int n, head[maxn], cnt;
uint dp[maxn], sum[maxn];

struct _edge {
	int v, next;
} g[maxn << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v) {
	g[cnt] = (_edge){v, head[u]};
	head[u] = cnt++;
}

inline void dfs(int x, int f) {
	dp[x] = sum[x] = 1;
	for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f) {
		dfs(g[i].v, x);
		dp[x] = ((ULL)dp[x] * (sum[g[i].v] + 1) + (ULL)sum[x] * dp[g[i].v]) % p;
		sum[x] = ((ULL)sum[x] * (sum[g[i].v] + 1)) % p;
	}
}

int main() {
	for(int T = iread(); T; T--) {
		n = iread();
		if(n == 1) {
			printf("1\n");
			continue;
		}
		for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;

		for(int i = 2; i <= n; i++) {
			int u = iread();
			add(u, i); add(i, u);
		}

		dfs(1, 0);

		uint ans = 0;
		for(int i = 1; i <= n; i++) ans = (ans + dp[i]) % p;
		printf("%u\n", ans);
	}
	return 0;
}


你可能感兴趣的:(TreeDP)