1. 程式人生 > >UESTC - 1147 求最短路方案數

UESTC - 1147 求最短路方案數

typedef gre pty uestc max prior rst pop type

這道題很是說明了記憶化搜索的重要性
瞎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 求最短路方案數