最短路模板题 但是其实很费时间 因为要看明白dij floyd 以及 dij优化 spfa优化 交了三次 大概是理解了
不过涉及到priority_queue的重载运算符问题 以后要在C++里面好好看看 现在不理解
Dijkstra ver:
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
#define INF 0x3F3F3F3F
using namespace std;
typedef pair<int, int> pii; int size, head[], point[], next[], val[];
int dis[], t, n; void add(int from, int to, int value)
{
point[size] = to;
next[size] = head[from];
val[size] = value;
head[from] = size++;
} struct cmp{
bool operator () (pii a, pii b){
return a.first > b.first;
}
}; void dijkstra(int s)
{
memset(dis, 0x3F, sizeof dis);
priority_queue<pii, vector<pii>, cmp> q;
q.push(make_pair(, s));
dis[s] = ;
while(!q.empty()){
pii u = q.top();
q.pop();
if(u.first > dis[u.second]) continue;
for(int i = head[u.second]; ~i; i = next[i]){
int j = point[i];
if(dis[j] > u.first + val[i]){
dis[j] = u.first + val[i];
q.push(make_pair(dis[j], j));
}
}
}
} int main()
{
while(~scanf("%d%d", &t, &n)){
size = ;
memset(head, -, sizeof head);
for(int i = ; i <= t; i++){
int from, to, value;
scanf("%d%d%d", &from, &to, &value);
add(from, to, value);
add(to, from, value);
}
dijkstra();
printf("%d\n", dis[n]);
}
return ;
}
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[], point[], next[], val[], 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[];
bool vis[];
memset(dis, 0x3f, sizeof dis);
memset(vis, false, sizeof vis);
queue<int> q;
dis[s] = ;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, -, 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(, n);
return ;
}