标签:
/* spfa + 判环 */ #include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<queue> #define ll long long using namespace std; const int maxn = 20005; const ll inf = 987654321234LL; struct edge{ int v; int w; int nxt; }e[maxn*3]; int n,m; int cnt,head[maxn],flag,vis[maxn],rd[maxn]; ll dis[maxn]; ll read(){ char ch=getchar(); ll x=0,f=1; while(!(ch>=‘0‘&&ch<=‘9‘)){if(ch==‘-‘)f=-1;ch=getchar();}; while(ch>=‘0‘&&ch<=‘9‘){x=x*10+(ch-‘0‘);ch=getchar();}; return x*f; } void ins(int u,int v,int w){ cnt++; e[cnt].v = v; e[cnt].w = w; e[cnt].nxt = head[u]; head[u] = cnt; } bool spfa(){ for(int i = 0;i <= n;i++){ dis[i] = inf; rd[i] = 0; } dis[1] = 0; flag++; queue<int> q; int now,to; q.push(1); vis[1] = flag; rd[1] = 1; while(!q.empty()){ now = q.front(); q.pop(); for(int i = head[now];i;i = e[i].nxt){ to = e[i].v; if(dis[to] > dis[now] + e[i].w){ dis[to] = dis[now] + e[i].w; if(vis[to] != flag){ vis[to] = flag; q.push(to); rd[to]++; if(rd[to] > n) return false; } } } vis[now] = 0; } if(dis[n] >= inf) return false; else return true; } int main(){ while(1){ cnt = 0; n = read(); m = read(); if(!n && !m) break; for(int i = 1;i <= n;i++) head[i] = 0; int g1,g2,c1,c2; for(int i = 1;i <= m;i++){ g1 = read(); g2 = read(); c1 = read(); c2 = read(); ins(g1,g2,c1); ins(g2,g1,c2); } if(spfa()) cout<<dis[n]<<endl; else cout<<"No such path"<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/hyfer/p/5925396.html