【BZOJ4562】[Haoi2016]食物链【DP】【DAG】【拓扑排序】

【题目链接】

傻逼题。

/* Pigonometry */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 100005, maxm = 200005, maxq = 200000;

int n, m, head[maxn], cnt, in[maxn], out[maxn], dp[maxn], q[maxq];
bool vis[maxn];

struct _edge {
	int v, next;
} g[maxm << 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++;
}

int main() {
	n = iread(); m = iread();
	for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;

	for(int i = 1; i <= m; i++) {
		int u = iread(), v = iread();
		out[u]++; in[v]++;
		add(u, v);
	}

	int h = 0, t = 0, u, i;
	for(int i = 1; i <= n; i++) {
		if(!in[i]) dp[q[t++] = i] = 1;
		if(in[i] && !out[i]) vis[i] = 1;
	}
	while(h != t) for(i = head[u = q[h++]]; ~i; i = g[i].next) {
		dp[g[i].v] += dp[u];
		in[g[i].v]--;
		if(!in[g[i].v]) q[t++] = g[i].v;
	}

	int ans = 0;
	for(int i = 1; i <= n; i++) if(vis[i]) ans += dp[i];

	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(【BZOJ4562】[Haoi2016]食物链【DP】【DAG】【拓扑排序】)