「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;
}