Codeforces Round #776 (Div. 3) G. Counting Shortcuts

#include
using namespace std;
#define int long long 
const int N=2e5+10;
const int mod=1e9+7;
int t,n,m,s,T;
vector<int> v[N];
int dp[N][2],dis[N],vis[N];
vector<int> g[N];
void run(int x){
    queue<int> q;q.push(x);
    dis[x]=0;dp[x][0]=1;
    while(q.size()){
        int tp=q.front();q.pop();
        // if(vis[tp]==1) continue;
        vis[tp]=1;
        for(auto to:v[tp]){
            dis[to]=min(dis[to],dis[tp]+1);
            if(dis[to]==dis[tp]+1)
                dp[to][0]+=dp[tp][0];dp[tp][0]%=mod;
            if(vis[to]==0) q.push(to),vis[to]=1;
        }
    }
    // for(int i=1;i<=n;i++) cout<
    for(int i=1;i<=n;i++) g[dis[i]].push_back(i);
    for(int i=0;i<=n;i++){
        for(auto from:g[i]){
            for(auto to:v[from]){
                if(dis[to]==dis[from]){
                    dp[from][1]+=dp[to][0];dp[from][1]%=mod;
                }
                if(dis[from]==dis[to]+1){
                    dp[from][1]+=dp[to][1];dp[from][1]%=mod;
                }   
            }
        }
    }
    cout<<(dp[t][0]+dp[t][1])%mod<<endl;

}
int32_t main(){
    scanf("%lld",&T);
    while(T--){
        scanf("%lld%lld%lld%lld",&n,&m,&s,&t);
        for(int i=0;i<=n;i++) dis[i]=1e9,vis[i]=0,dp[i][0]=dp[i][1]=0,v[i].clear(),g[i].clear();
        for(int i=1;i<=m;i++){
            int x,y;scanf("%lld%lld",&x,&y);
            v[x].push_back(y);
            v[y].push_back(x);
        }
        run(s);

    }
}

你可能感兴趣的:(acm,动态规划,c++,算法)