标签:
3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
/*dijkstra*/ #include<cstdio> #include<algorithm> #define MAX 0x3f3f3f using namespace std; int dis[211],vis[211]; int len[211][211]; int n,m,s,t; int min(int x,int y) { if(x >= y) return y; return x; } void dijkstra() { int i,j,k; for( i = 0; i < n; i++) { dis[i] = MAX; vis[i] = 0; } dis[s] = 0; while(1) { k = -1; for( i = 0; i < n ; i++) if(!vis[i] && (k==-1 ||dis[i] < dis[k])) k = i; if(k == -1) break; vis[k] = 1; for(i = 0; i < n; i++) dis[i] = min( dis[i], dis[k]+len[i][k]); } if(dis[t] == MAX) printf("-1\n"); else printf("%d\n",dis[t]); } int main() { int i,j,k,a,b,x; while(scanf("%d%d",&n,&m)!=EOF) { for( i = 0; i < n; i++) for( j = 0; j < n; j++) len[i][j] = MAX; while(m--) { scanf("%d%d%d",&a,&b,&x); if(len[a][b] > x) { len[a][b] = x; len[b][a] = x; } } scanf("%d%d",&s, &t); dijkstra(); } return 0; } /*spfa*/ #include<stdio.h> #include<string.h> #include<stdlib.h> #include<queue> #include<vector> #define INF 0x3f3f3f #include<algorithm> using namespace std; int n,m; int head[2100],edgenum,dis[2100]; bool vis[2100]; struct node{ int start,end,len,next; }p[20010]; void add(int u,int v,int w) { node E = {u,v,w,head[u]}; p[edgenum] = E; head[u] = edgenum++; } void spfa(int s,int t) { memset(vis,0,sizeof(vis)); memset(dis,0x3f,sizeof(dis)); queue<int> q; q.push(s); dis[s] = 0; vis[s] = 1; while(!q.empty()) { int u = q.front(); q.pop(); vis[u] = 0; for(int i = head[u]; i!=-1;i=p[i].next) { int v = p[i].end; if(dis[v]>dis[u]+p[i].len) { dis[v]=dis[u]+p[i].len; if(!vis[v]) { vis[v] =1; q.push(v); } } } } if(dis[t]>10000) printf("-1\n"); else printf("%d\n",dis[t]); } int main() { int i,j,k; while(scanf("%d%d",&n,&m)!=EOF) { memset(head,-1,sizeof(head)); edgenum = 0; int a,b,c; while(m--) { scanf("%d%d%d",&a,&b,&c); add(a,b,c); add(b,a,c); } int s1,e1; scanf("%d%d",&s1,&e1); spfa(s1,e1); } return 0; } /*floyd*/ #include<stdio.h> #include<string.h> #define min(a,b) a>b?b:a #define INF 0x3f3f3f3f int n,m; int dis[211][211]; void floyd() { int i,j,k; for(k = 0; k < n; k++) for(i = 0; i < n; i++) for(j = 0; j < n; j++) dis[i][j] = min( dis[i][j], dis[i][k]+dis[k][j] ); } int main() { int i,j,k; while(scanf("%d%d",&n,&m)!=EOF) { int a,b,x; for(i = 0;i < n; i++) { for(j = 0; j < n; j++) if(i==j) dis[i][j] = 0; else dis[i][j] = INF; } while(m--) { scanf("%d%d%d",&a,&b,&x); if(dis[a][b] > x) dis[a][b] = dis[b][a] =x; } int from,to; scanf("%d%d",&from,&to); floyd(); if(dis[from][to]==INF) printf("-1\n"); else printf("%d\n",dis[from][to]); } return 0; }
版权声明:原创文章,若要转载,请与博主联系,谢谢
标签:
原文地址:http://blog.csdn.net/liu6886/article/details/47839007