SZU 2015 Winter Training Day#6
Description
Input
Output
Sample Input
3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
Sample Output
2 -1
我的代码dijkstra 算法
#include <stdio.h> #include <algorithm> #include <iostream> using namespace std; #define INF 0x3f3f3f3f int mtx[205][205]; int vis[205]; int dist[205]; int main() { int t,n,i,p,j,k,m,kk,pp,begin,end,kkpp; while( scanf("%d%d",&n,&m)!=EOF) { memset(mtx,INF,sizeof(mtx)); memset(vis,0,sizeof(vis)); memset(dist,INF,sizeof(dist)); int minway; for (p=1;p<=m;p++) { scanf("%d%d",&kk,&pp); scanf("%d",&kkpp); kk++; pp++; if (kkpp<mtx[kk][pp]) { mtx[kk][pp]=kkpp; mtx[pp][kk]=mtx[kk][pp]; } } scanf("%d%d",&begin,&end); begin++; end++; //11 for (j=1;j<=n;j++) //创建第一组dist { // if ( (mtx[begin][j])!=0 || (begin==j) ) dist[j]=mtx[begin][j]; // else // dist[j]=INF; } dist[begin]=0; vis[begin]=1; for (k=2;k<=n;k++) //不断更新dist { minway=INF; int minpoint; for (j=1;j<=n;j++) //不断更新dist { if (vis[j]==0 && dist[j]<minway) //找到最小加权边与点 { minway=dist[j]; minpoint=j; } } vis[minpoint]=1; for (j=1;j<=n;j++) //不断更新dist { //if (dist[j]==INF&&vis[j]!=1) {br=1;break;} if ( mtx[minpoint][j]+minway<dist[j]&&vis[j]!=1) dist[j]=mtx[minpoint][j]+minway; } } if (dist[end]==INF ) printf("-1\n"); else printf("%d\n",dist[end]); } return 0; }
nlogn 堆优化:
#include <cstdio> #include <cmath> #include <cstring> #include <string> #include <algorithm> #include <iostream> #include <queue> #include <map> #include <set> #include <vector> using namespace std; #define INF 0x7f7f7f7f const __int64 maxn = 100005; struct node { int x;int v; node(){} node (int i,int j) { x=i;v=j; } bool operator < (const node &b) const { return v>b.v; } }; vector <node> tm[maxn]; int dist[205]; priority_queue<node> que; int main() { int n,r,i; int a,b,c; while( scanf("%d%d",&n,&r)!=EOF) { memset(dist,INF,sizeof(dist)); for (i=1;i<=n;i++) { tm[i].clear(); } for (i=1;i<=r;i++) { scanf("%d %d %d",&a,&b,&c); a++; b++; tm[a].push_back(node(b,c)); tm[b].push_back(node(a,c)); } int st,ed; scanf("%d%d",&st,&ed); st++; ed++; dist[st]=0; que.push(node(st,0)); int minway; int minpoint; while(!que.empty()) { node p=que.top(); que.pop(); minpoint=p.x; minway=p.v; // vis[minpoint]=1; for (i=0;i<tm[minpoint].size();i++) { int x=tm[minpoint][i].x; int v=tm[minpoint][i].v; if ( v+minway<dist[x]/*&&vis[x]!=1*/) { dist[x]=v+minway; que.push(node(x,dist[x])); } } } if (dist[ed]==INF) printf("-1\n"); else printf("%d\n",dist[ed]); } return 0; }