题目传送门

题解

  • 这道题就是要求求从点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];//f[i]: 从i到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];//如果点x到n的方案已经更新过,
	//那么直接返回 
	for(int i=h[x]; i!=-1; i=ne[i])
	{
   
		//点x到n的最大方案数 = 已知从点x到n的方案 + 未知从点x到n的方案 
	    f[x] = (f[x] + dfs(e[i]))%mod;
	}
	//最后求得f[x]后返回给上一层 
	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;
 }