传送门:【POJ】1949 Chores
题目分析:建反图,然后DAG最长路
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
#define REP( i , a , b ) for ( int i = ( a ) ; i < ( b ) ; ++ i )
#define FOR( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define REV( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define travel( e , H , u ) for ( Edge* e = H[u] ; e ; e = e -> next )
#define CLR( a , x ) memset ( a , x , sizeof a )
const int MAXN = 10005 ;
const int MAXE = 1000005 ;
const int INF = 0x3f3f3f3f ;
struct Edge {
int v ;
Edge* next ;
} E[MAXE] , *H[MAXN] , *cur ;
int n ;
int in[MAXN] , val[MAXN] ;
int Q[MAXN] , head , tail ;
int d[MAXN] ;
void init () {
cur = E ;
CLR ( H , 0 ) ;
CLR ( in , 0 ) ;
}
void addedge ( int u , int v ) {
cur -> v = v ;
cur -> next = H[u] ;
H[u] = cur ++ ;
}
void topo () {
CLR ( d , 0 ) ;
head = tail = 0 ;
FOR ( i , 1 , n ) if ( !in[i] ) Q[tail ++] = i , d[i] = val[i] ;
while ( head != tail ) {
int u = Q[head ++] ;
travel ( e , H , u ) {
int v = e -> v ;
if ( d[v] < d[u] + val[v] ) d[v] = d[u] + val[v] ;
if ( -- in[v] == 0 ) Q[tail ++] = v ;
}
}
}
void scanf ( int& x , char c = 0 ) {
while ( ( c = getchar () ) < '0' || c > '9' ) ;
x = c - '0' ;
while ( ( c = getchar () ) >= '0' && c <= '9' ) x = x * 10 + c - '0' ;
}
void solve () {
int v , m ;
init () ;
FOR ( i , 1 , n ) {
scanf ( val[i] ) ;
scanf ( m ) ;
while ( m -- ) {
scanf ( v ) ;
addedge ( v , i ) ;
++ in[i] ;
}
}
topo () ;
int ans = 0 ;
FOR ( i , 1 , n ) if ( d[i] > ans ) ans = d[i] ;
printf ( "%d\n" , ans ) ;
}
int main () {
while ( ~scanf ( "%d" , &n ) ) solve () ;
return 0 ;
}