最短路裸题,dijkstra+邻接表水过
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 102
#define MAXM 10001
#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].w = w; edge[e_cnt].v = v;
edge[e_cnt].next = head[u]; head[u] = e_cnt ++;
swap(u, v);
edge[e_cnt].w = w; edge[e_cnt].v = v;
edge[e_cnt].next = head[u]; head[u] = e_cnt ++;
}
int dijkstra(int src, int des, int vertex)
{
int u, v, min_val;
fill(dis, dis+vertex+1, INF);
memset(used, 0, sizeof(used));
for(int i = head[src]; -1 != i; i = edge[i].next) {
v = edge[i].v;
dis[v] = min(dis[v], edge[i].w);
}
used[src] = 1; dis[src] = 0;
for(int i = 1; i < vertex; i ++) {
min_val = INF;
for(int j = 1; j <= vertex; j ++) {
if( !used[j] && min_val > dis[j] ) {
min_val = dis[j]; u = 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 dis[des];
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int vertex, arc, u, v, w;
while( scanf("%d %d", &vertex, &arc) && 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);
}
printf("%d\n", dijkstra(1, vertex, vertex));
}
return 0;
}
09-04
09-04
09-04
09-04