题目传送门
题解
这道题就是要求求从点1到点n的方案数字,采用记忆化搜索,如果直接暴力搜索只能能过%90, 定义f[i] : 表示从点i到n的最大方案数字,初始化f[n] = 1 其余见代码
AC代码
#include <bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
const int N = 5e5 + 9 ;
const int mod = 20010905 ;
int n, m;
int a, b, w;
int h[ N] , e[ N] , ne[ N] , idx;
int f[ N] ;
void add ( int a, int b)
{
e[ idx] = b;
ne[ idx] = h[ a] ;
h[ a] = idx++ ;
}
int dfs ( int x)
{
if ( f[ x] ) return f[ x] ;
for ( int i= h[ x] ; i!= - 1 ; i= ne[ i] )
{
f[ x] = ( f[ x] + dfs ( e[ i] ) ) % mod;
}
return f[ x] ;
}
int main ( )
{
mem ( h, - 1 ) ;
scanf ( "%d%d" , & n, & m) ;
for ( int i= 0 ; i< m; i++ )
{
scanf ( "%d%d%d" , & a, & b, & w) ;
add ( a, b) ;
}
f[ n] = 1 ;
printf ( "%d\n" , dfs ( 1 ) ) ;
return 0 ;
}
暴力搜索代码
#include <bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
const int N = 5e5 + 9 ;
const int mod = 20010905 ;
int n, m;
int a, b, w;
int h[ N] , e[ N] , ne[ N] , idx;
int f[ N] ;
bool st[ N] ;
int cnt = 0 ;
void add ( int a, int b)
{
e[ idx] = b;
ne[ idx] = h[ a] ;
h[ a] = idx++ ;
}
void dfs ( int x)
{
if ( x== n)
{
cnt++ ;
cnt% = mod ;
return ;
}
for ( int i= h[ x] ; i!= - 1 ; i= ne[ i] )
{
if ( ! st[ e[ i] ] )
{
st[ e[ i] ] = true ;
dfs ( e[ i] ) ;
st[ e[ i] ] = false ;
}
}
}
int main ( )
{
mem ( h, - 1 ) ;
scanf ( "%d%d" , & n, & m) ;
for ( int i= 0 ; i< m; i++ )
{
scanf ( "%d%d%d" , & a, & b, & w) ;
add ( a, b) ;
}
f[ n] = 1 ;
dfs ( 1 ) ;
printf ( "%d\n" , cnt) ;
return 0 ;
}