最短路模板题 但是其实很费时间 因为要看明白dij floyd 以及 dij优化 spfa优化 交了三次 大概是理解了
不过涉及到priority_queue的重载运算符问题 以后要在C++里面好好看看 现在不理解
Dijkstra ver:
1 #include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <cmath> 5 #include <cstring> 6 #include <queue> 7 #include <map> 8 #include <set> 9 #include <vector> 10 #include <algorithm> 11 #define INF 0x3F3F3F3F 12 using namespace std; 13 typedef pair<int, int> pii; 14 15 int size, head[101000], point[401000], next[401000], val[401000]; 16 int dis[101000], t, n; 17 18 void add(int from, int to, int value) 19 { 20 point[size] = to; 21 next[size] = head[from]; 22 val[size] = value; 23 head[from] = size++; 24 } 25 26 struct cmp{ 27 bool operator () (pii a, pii b){ 28 return a.first > b.first; 29 } 30 }; 31 32 void dijkstra(int s) 33 { 34 memset(dis, 0x3F, sizeof dis); 35 priority_queue<pii, vector<pii>, cmp> q; 36 q.push(make_pair(0, s)); 37 dis[s] = 0; 38 while(!q.empty()){ 39 pii u = q.top(); 40 q.pop(); 41 if(u.first > dis[u.second]) continue; 42 for(int i = head[u.second]; ~i; i = next[i]){ 43 int j = point[i]; 44 if(dis[j] > u.first + val[i]){ 45 dis[j] = u.first + val[i]; 46 q.push(make_pair(dis[j], j)); 47 } 48 } 49 } 50 } 51 52 int main() 53 { 54 while(~scanf("%d%d", &t, &n)){ 55 size = 0; 56 memset(head, -1, sizeof head); 57 for(int i = 1; i <= t; i++){ 58 int from, to, value; 59 scanf("%d%d%d", &from, &to, &value); 60 add(from, to, value); 61 add(to, from, value); 62 } 63 dijkstra(1); 64 printf("%d\n", dis[n]); 65 } 66 return 0; 67 }
Spfa ver:
#include <iostream> #include <string> #include <cstdio> #include <cmath> #include <cstring> #include <queue> #include <map> #include <set> #include <algorithm> #define INF 0x3F3F3F3F using namespace std; int head[100010], point[400010], next[400010], val[400010], size; void add(int from, int to, int value) { point[size] = to; val[size] = value; next[size] = head[from]; head[from] = size++; point[size] = from; val[size] = value; next[size] = head[to]; head[to] = size++; } void spfa(int s, int t) { int dis[100010]; bool vis[100010]; memset(dis, 0x3f, sizeof dis); memset(vis, false, sizeof vis); queue<int> q; dis[s] = 0;vis[s] = true; q.push(s); while(!q.empty()){ int u = q.front(); q.pop(); vis[u] = false; for(int i = head[u]; ~i; i = next[i]){ int j = point[i]; if(dis[j] > dis[u] + val[i]){ dis[j] = dis[u] + val[i]; if(!vis[j]){ q.push(j); vis[j] = true; } } } } printf("%d\n", dis[t]); } int main() { int t, n; memset(head, -1, sizeof head); scanf("%d%d", &t, &n); while(t--){ int a, b, value; scanf("%d%d%d", &a, &b, &value); add(a, b, value); } spfa(1, n); return 0; }
时间: 2024-10-06 18:02:49