HDU 2544 最最裸的最短路
Dijkstra + Heap
Problem : 2544 ( 最短路 ) Judge Status : Accepted
RunId : 8360313 Language : G++ Author : CherryChou
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
RunId : 8360313 Language : G++ Author : CherryChou
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
# include<cstdio> # include<cstring> # include<algorithm> # include<queue> # include<map> # include<vector> # include<utility> using namespace std; const int inf=1<<25; const int maxn=105; const int maxm=20005; typedef pair<int,int> node; struct edge { int u,v,w,next; } e[maxm]; struct cmp { bool operator()(const node &a,const node &b)const { return a.second>b.second; } }; int num,head[maxn]; int dis[maxn],n,m; bool vis[maxn]; priority_queue<node,vector<node>,cmp> q; inline void add(int u,int v,int w) { e[num].u=u; e[num].v=v; e[num].w=w; e[num].next=head[u]; head[u]=num++; } void addedge(int u,int v,int w) { add(u,v,w); add(v,u,w); } void dijkstra(int s) { int i,u,v; dis[s]=0; q.push(make_pair(s,dis[s])); while(!q.empty()) { u=q.top().first; q.pop(); if(vis[u]) continue; vis[u]=1; for(i=head[u];i!=-1;i=e[i].next) { v=e[i].v; if(!vis[v]&&dis[u]+e[i].w<dis[v]) { dis[v]=dis[u]+e[i].w; q.push(make_pair(v,dis[v])); } } } } void init() { num=0; memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); for(int i=0;i<=n;i++) { dis[i]=inf; vis[i]=0; } } int main() { while(~scanf("%d%d",&n,&m),n+m) { init(); int s,t,w; while(m--) { scanf("%d%d%d",&s,&t,&w); addedge(s,t,w); } dijkstra(1); printf("%d\n",dis[n]); } return 0; }
SPFA
Problem : 2544 ( 最短路 ) Judge Status : Accepted
RunId : 8360334 Language : G++ Author : CherryChou
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
RunId : 8360334 Language : G++ Author : CherryChou
Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
# include<cstdio> # include<cstring> # include<algorithm> # include<queue> using namespace std; const int inf=1<<25; const int maxn=105; const int maxm=20005; typedef pair<int,int> node; struct edge { int u,v,w,next; } e[maxm]; int num,head[maxn]; int dis[maxn],n,m; bool vis[maxn]; queue<int> q; inline void add(int u,int v,int w) { e[num].u=u; e[num].v=v; e[num].w=w; e[num].next=head[u]; head[u]=num++; } void addedge(int u,int v,int w) { add(u,v,w); add(v,u,w); } void spfa(int s) { int i,u,v; dis[s]=0; q.push(s); vis[s]=1; while(!q.empty()) { u=q.front(); q.pop(); for(i=head[u];i!=-1;i=e[i].next) { v=e[i].v; if(dis[u]+e[i].w<dis[v]) { dis[v]=dis[u]+e[i].w; if(!vis[v]) { q.push(v); vis[v]=1; } } } vis[u]=0; } } void init() { num=0; memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) { dis[i]=inf; vis[i]=0; } } int main() { while(~scanf("%d%d",&n,&m),n+m) { init(); int s,t,w; while(m--) { scanf("%d%d%d",&s,&t,&w); addedge(s,t,w); } spfa(1); printf("%d\n",dis[n]); } return 0; }