单源路径的最短路问题这里写了2个版本,spfa和dijkstra(没有优化)
//spfa
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
#define MAXN 201
#define MAXM 1001
#define INF 0x3f3f3f3f
struct Edge {
int v, w, next;
}edge[MAXM];
int e_cnt, head[MAXN], dis[MAXN], used[MAXN];
void insert_arc(int u, int v, int w)
{
edge[e_cnt].v = v; edge[e_cnt].w = w;
edge[e_cnt].next = head[u]; head[u] = e_cnt ++;
swap(u, v);
edge[e_cnt].v = v; edge[e_cnt].w = w;
edge[e_cnt].next = head[u]; head[u] = e_cnt ++;
}
int spfa(int src, int des, int vertex)
{
int u, v;
queue<int> q;
fill(dis, dis+vertex, INF);
memset(used, 0, sizeof(used));
dis[src] = 0; used[src] = 1;
q.push(src);
while( !q.empty() ) {
u = q.front(); q.pop(); used[u] = 0;
for(int i = head[u]; -1 != i; i = edge[i].next) {
v = edge[i].v;
if( dis[v] > dis[u]+edge[i].w ) {
dis[v] = dis[u]+edge[i].w;
if( !used[v] ) {
q.push(v); used[v] = 1;
}
}
}
}
return (INF == dis[des])? -1 : dis[des];
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int vertex, arc, src, des, u, v, w;
while( ~scanf("%d %d", &vertex, &arc) ) {
e_cnt = 0; memset(head, -1, sizeof(head));
for(int i = 0; i < arc; i ++) {
scanf("%d %d %d", &u, &v, &w);
insert_arc(u, v, w);
}
scanf("%d %d", &src, &des);
printf("%d\n", spfa(src, des, vertex));
}
return 0;
}
//dijkstra
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 201
#define MAXM 1001
#define INF 0x3f3f3f3f
struct Edge {
int v, w, next;
}edge[MAXM];
int e_cnt, head[MAXN], dis[MAXN], used[MAXN];
void insert_arc(int u, int v, int w)
{
edge[e_cnt].v = v; edge[e_cnt].w = w;
edge[e_cnt].next = head[u]; head[u] = e_cnt ++;
swap(u, v);
edge[e_cnt].v = v; edge[e_cnt].w = w;
edge[e_cnt].next = head[u]; head[u] = e_cnt ++;
}
int dijkstra(int src, int des, int vertex)
{
int min_val, u, v;
fill(dis, dis+vertex, INF);
memset(used, 0, sizeof(used));
for(int i = head[src]; -1 != i; i = edge[i].next) {
dis[edge[i].v] = min(dis[edge[i].v], edge[i].w); //有重边,这里注意了
}
dis[src] = 0; used[src] = 1;
for(int i = 1; i < vertex; i ++) {
min_val = INF;
for(int j = 0; j < vertex; j ++) {
if( !used[j] && min_val > dis[j] ) {
u = j; min_val = dis[j];
}
}
used[u] = 1;
for(int j = head[u]; -1 != j; j = edge[j].next) {
v = edge[j].v;
if( !used[v] && dis[v] > dis[u]+edge[j].w ) {
dis[v] = dis[u]+edge[j].w;
}
}
}
return (INF == dis[des])? -1 : dis[des];
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int vertex, arc, src, des, u, v, w;
while( ~scanf("%d %d", &vertex, &arc) ) {
e_cnt = 0; memset(head, -1, sizeof(head));
for(int i = 0; i < arc; i ++) {
scanf("%d %d %d", &u, &v, &w);
insert_arc(u, v, w);
}
scanf("%d %d", &src, &des);
printf("%d\n", dijkstra(src, des, vertex));
}
return 0;
}
hdu_1874
最新推荐文章于 2019-07-07 16:57:12 发布