码迷,mamicode.com
首页 > 其他好文 > 详细

UESTC - 1147 求最短路方案数

时间:2018-02-14 22:38:44      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:read   size   重要性   c++   max   别人   set   但我   print   

这道题很是说明了记忆化搜索的重要性
瞎bfs递推半天发现没卵用(也许是姿势不对,但我认为树形或图形dfs明显好写并且很好正确地递推)
参考了别人的写法,总感觉自己的实现能力太弱了
还有题目是1e9+9,送了3WA

/*H E A D*/
int to[maxn<<1],nxt[maxn<<1],cost[maxn<<1],head[maxn],tot;
void init(){
    memset(head,-1,sizeof head);
    tot=0;
} 
void add(int u,int v,int w){
    to[tot]=v;cost[tot]=w;nxt[tot]=head[u];head[u]=tot++;
    swap(u,v);
    to[tot]=v;cost[tot]=w;nxt[tot]=head[u];head[u]=tot++;
}
int dp[maxn];
int dis[maxn];
int n,m;
typedef pair<int,int> P;
void dijkstra(int s){
    memset(dis,oo,sizeof dis);
    priority_queue<P,vector<P>,greater<P> > que;
    que.push(P(s,0));
    dis[s]=0; dp[s]=1;
    while(!que.empty()){
        P p=que.top(); que.pop();
        int u=p.first;
        if(dis[u]<p.second)continue;
        erep(i,u){
            int v=to[i],w=cost[i];
            if(dis[v]>dis[u]+w){
                dis[v]=dis[u]+w;
                que.push(P(v,dis[v]));
            }
        }
    }
}
bool vis[maxn];
bool findzero(int u){
    if(u==1)return 0;
    bool flag=0;
    erep(i,u){
        int v=to[i],w=cost[i];
        if(!vis[i]&&dis[u]==dis[v]+w){
            vis[i]=vis[i^1]=1;
            if(w==0) return 1;
            if(findzero(v)) return 1;
        }
    }
    return 0;
}
int DP(int u){
    if(~dp[u]) return dp[u];
    dp[u]=0;
    erep(i,u){
        int v=to[i],w=cost[i];
        if(!vis[i]&&dis[u]==dis[v]+w){
            vis[i]=1;
            vis[i^1]=1;
            dp[u]=(1ll*dp[u]+DP(v))%mod;
        }
    }
    return dp[u];
}
int main(){
    while(cin>>n>>m){
        init();
        rep(i,1,m){
            int u=read();
            int v=read();
            int w=read();
            add(u,v,w);
        }
        dijkstra(1);
        memset(vis,0,sizeof vis);
        bool flag=findzero(n);
        if(flag) println(-1);
        else{
            memset(dp,-1,sizeof dp);
            memset(vis,0,sizeof vis);
            dp[1]=1;
            println(DP(n));         
        }
    }
    return 0;
}

一组测试用数据

4 5
1 2 2
1 3 1
2 3 1
2 4 1
3 4 2

ans:3

UESTC - 1147 求最短路方案数

标签:read   size   重要性   c++   max   别人   set   但我   print   

原文地址:https://www.cnblogs.com/caturra/p/8448995.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!