1874-畅通工程续
http://acm.hdu.edu.cn/showproblem.php?pid=1874
题意:略。
思路:最短路dijkstra模板,不过要先要把题里输入的把两点间距离赋值给构建的矩阵。
dijkstra算法
#include<bits/stdc++.h> using namespace std; #define inf 99999999 #define maxn 210 int maps[maxn][maxn], dis[maxn], visited[maxn]; int n, m; using namespace std; int dijkstra(int s, int t) { for(int i = 0; i < n; i++) { dis[i] = maps[s][i]; visited[i] = 0; } dis[s] = 0; visited[s] = 1; int temp, k; //这个循环的意思是把这一点的这一行都找到最短路径 for(int i = 0; i < n; i++) { temp = inf; //找最小距离的一点 for(int j = 0; j < n; j++) { if(visited[j] == 0 && temp > dis[j]) { k = j; temp = dis[j]; } } //这一点没有与别的点相连,跳出循环 if(temp == inf) break; visited[k] = 1; for(int j = 0; j < n; j++) { if(dis[j] > dis[k] + maps[k][j]) dis[j] = dis[k] + maps[k][j]; } } if(dis[t] == inf) return -1; else return dis[t]; } int main() { int a, b, x, s, t, ans; while(scanf("%d %d", &n, &m) != EOF) { //构建矩阵,是各点之间的距离 for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) maps[i][j] = (i == j ? 0 : inf); while(m--) { scanf("%d%d%d", &a, &b, &x); //把两点间距离赋值给矩阵 if(x < maps[a][b]) maps[a][b] = maps[b][a] = x; } scanf("%d %d", &s, &t); ans = dijkstra(s, t); printf("%d\n", ans); } return 0; }
floyd算法:
待补充
SPFA算法:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <queue> #include <algorithm> using namespace std; #define inf 99999999 #define maxn 210 int maps[maxn][maxn]; int visited[maxn],dis[maxn]; int n,m; queue<int> q; int spfa(int s,int t) { for(int i = 0;i < n;i++) { dis[i] = inf; visited[i] = 0; } while(!q.empty()) q.pop(); dis[s] = 0; visited[s] = 1; q.push(s);//起点入队 while(!q.empty()) { int temp = q.front(); q.pop(); visited[temp] = 0; for(int i = 0;i < n;i++) { if(dis[i] > dis[temp] + maps[temp][i]) { dis[i] = dis[temp] + maps[temp][i]; if(visited[i] == 0) { visited[i] = 1; q.push(i);//当前最短距离的点入队 } } } } if(dis[t] == inf) return -1; else return dis[t]; } int main() { int a,b,x,s,t,ans; while(scanf("%d %d",&n,&m) != EOF) { for(int i = 0;i < n;i++) for(int j = 0;j < n;j++) maps[i][j] = (i == j ? 0 : inf); while(m--) { scanf("%d %d %d",&a,&b,&x); if(x < maps[a][b]) maps[a][b] = maps[b][a] = x; } scanf("%d %d",&s,&t); ans = spfa(s,t); printf("%d\n",ans); } return 0; }