「HAOI2016」食物链

题目链接

解题思路

简单的DAG上DP即可。

参考程序

#include <bits/stdc++.h>
using namespace std;

const int Maxn = 100010;
const int Maxm = 200010;
struct edge {
	int To, Next;
};
edge Edge[ Maxm ];
int Start[ Maxn ], Used;
int n, m, In[ Maxn ], Out[ Maxn ], Dp[ Maxn ], L, R, Queue[ Maxn ], Count[ Maxn ];

inline void AddEdge( int x, int y ) {
	Edge[ ++Used ] = ( edge ) { y, Start[ x ] };
	Start[ x ] = Used;
	return;
}

int main() {
	scanf( "%d%d", &n, &m );
	for( int i = 1; i <= m; ++i ) {
		int x, y; scanf( "%d%d", &x, &y );
		AddEdge( x, y );
		++In[ y ]; ++Out[ x ];
	}
	for( int i = 1; i <= n; ++i )
		if( !In[ i ] ) {
			Dp[ i ] = 1;
			Queue[ ++R ] = i;
		}
	memcpy( Count, In, sizeof( Count ) );
	while( L < R ) {
		int u = Queue[ ++L ];
		for( int t = Start[ u ]; t; t = Edge[ t ].Next ) {
			int v = Edge[ t ].To;
			Dp[ v ] += Dp[ u ];
			if( --In[ v ] == 0 ) Queue[ ++R ] = v;
		}
	}
	int Ans = 0;
	for( int i = 1; i <= n; ++i ) 
		if( Count[ i ] && !Out[ i ] ) Ans += Dp[ i ];
	printf( "%d\n", Ans );
	return 0;
}

posted @ 2019-07-25 15:21  chy_2003  阅读(125)  评论(0编辑  收藏  举报