标签:
ime Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 32657 Accepted Submission(s): 11929
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define INF 1<<30 using namespace std; int n,m; int st,ed; int w[205][205]; int d[205],vis[205]; void read_graph()//邻接矩阵存储图 { for(int i=0;i<205;++i) for(int j=0;j<205;++j) w[i][j]=INF; int u,v,c; for(int i=0;i<m;++i){ cin>>u>>v>>c; if(c>w[u][v]) continue;//WA了十几次,最终看了DIC才知道相同路径的权值可能不同,应保存较小的 w[u][v]=c;//如 2 3 2和2 3 4 后一个应舍弃 w[v][u]=c; } cin>>st>>ed; } void dij() { memset(vis,0,sizeof(vis)); for(int i=0;i<=n;++i) d[i]=INF; d[st]=0; for(int i=0;i<n;++i){ int x,m=INF; for(int j=0;j<n;++j) if(!vis[j]&&d[j]<=m) m=d[x=j]; vis[x]=1; for(int j=0;j<n;++j) if(w[x][j]!=INF) d[j]=min(d[j],d[x]+w[x][j]); } } void solve() { read_graph(); dij(); //for(int i=0;i<n;++i) cout<<d[i]<<endl; if(d[ed]==INF) cout<<-1<<endl;//若起点到终点的最短路仍为初始值INF,则不通 else cout<<d[ed]<<endl; } int main() { //freopen("case.txt","r",stdin); while(~scanf("%d%d",&n,&m)) solve(); return 0; }
-1
标签:
原文地址:http://www.cnblogs.com/orchidzjl/p/4409303.html