Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 42585 Accepted Submission(s): 18653
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
AC-code:
Dijkstra:
#include<cstdio> #define max 0x3f3f3f3f #define min(a,b) (a>b?b:a) int n,dis[105],cost[105][105]; void dijkstra(int a) { int i,vis[105]; for(i=1;i<=n;i++) { dis[i]=max; vis[i]=0; } dis[a]=0; while(1) { int v=-1; for(i=1;i<=n;i++) if(!vis[i]&&(v==-1||dis[i]<dis[v])) v=i; if(v==-1) break; vis[v]=1; for(i=1;i<=n;i++) dis[i]=min(dis[i],dis[v]+cost[v][i]); } } int main() { int m,i,j,a,b,c; while(scanf("%d%d",&n,&m),n||m) { for(i=1;i<=n;i++) for(j=1;j<=n;j++) cost[i][j]=max; for(i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); cost[a][b]=cost[b][a]=min(cost[a][b],c); } dijkstra(1); printf("%d\n",dis[n]); } return 0; }
SPFA:
#include<cstdio> #include<queue> #include<cstring> #define INF 0x3f3f3f3f int dis[105],vis[105],n,head[105*105],num; using namespace std; struct node { int from,to,val,next; }A[105*105]; void spfa(int sx) { queue<int>q; memset(dis,INF,sizeof(dis)); memset(vis,0,sizeof(vis)); q.push(sx); dis[sx]=0; vis[sx]=1; while(!q.empty()) { int u=q.front(); q.pop(); vis[u]=0; for(int i=head[u];i!=-1;i=A[i].next) { int v=A[i].to; if(dis[v]>dis[u]+A[i].val) { dis[v]=dis[u]+A[i].val; if(!vis[v]) { vis[v]=1; q.push(v); } } } } printf("%d\n",dis[n]); } void chan(int a,int b,int c) { node B={a,b,c,head[a]}; A[num]=B; head[a]=num++; } int main() { int i,m,a,b,c; while(scanf("%d%d",&n,&m),n||m) { num=0; memset(head,-1,sizeof(head)); for(i=0;i<m;i++) { scanf("%d%d%d",&a,&b,&c); chan(a,b,c); chan(b,a,c); } spfa(1); } return 0; }