KFSTB - Help the Commander in Chief - SPOJ Solution C++

  Problem Link : KFSTB 


👉 Hint : Use DFS with DP

 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;
 
#define m 1000000007
 
vector<int> adj[10001];
long long int dp[10001];
 
long long int dfs(int v,int t)
{
    long long int ans=0;
    
    if(dp[v]!=-1)
        return dp[v];
    
    if(v==t)
        return 1;
    for(int i=0;i<adj[v].size();i++)
    {
        dp[adj[v][i]]=dfs(adj[v][i],t);
        ans=(ans+dp[adj[v][i]])%m;    }
    return dp[v]=ans;
}
 
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        for(int i=0;i<10001;i++)
            dp[i]=-1;
        int c,b,s,t,x,y;
        cin>>c>>b>>s>>t;
        for(int i=1;i<=c;i++)
            adj[i].clear();
        for(int i=1;i<=b;i++)
        {
            cin>>x>>y;
            adj[x].push_back(y);
        }
        cout<<dfs(s,t)<<endl;
    }
}  

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!