最短路
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
#define MAXN 20010
#define INF 0X3F3F3F3F
struct Edge
{
int u, v, w;
int next;
}edge[MAXN*5];
int first[MAXN], d[MAXN];
int n, m, cnt;
int s, e;
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
void spfa(int src)
{
queue<int> q;
bool inq[MAXN] = {0};
for(int i = 0; i < n; i++) d[i] = (i == src)?0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0;
for(int e = first[x]; e != -1; e = edge[e].next)
{
int v = edge[e].v, w = edge[e].w;
if(d[v] > d[x] + w)
{
d[v] = d[x] + w;
if(!inq[v])
{
inq[v] = 1;
q.push(v);
}
}
}
}
int ans = d[e];
if(ans == INF) printf("unreachable\n");
else printf("%d\n", ans);
}
void read_graph(int u, int v, int w)
{
edge[cnt].v = v, edge[cnt].w = w;
edge[cnt].next = first[u], first[u] = cnt++;
}
int main()
{
int T, times = 0;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d%d%d%d", &n, &m, &s, &e);
while(m--)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
read_graph(u, v, w);
read_graph(v, u, w);
}
printf("Case #%d: ", ++times);
spfa(s);
}
return 0;
}
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
#define MAXN 20010
#define INF 0X3F3F3F3F
struct Edge
{
int u, v, w;
int next;
}edge[MAXN*5];
int first[MAXN], d[MAXN];
int n, m, cnt;
int s, e;
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
void spfa(int src)
{
queue<int> q;
bool inq[MAXN] = {0};
for(int i = 0; i < n; i++) d[i] = (i == src)?0:INF;
q.push(src);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x] = 0;
for(int e = first[x]; e != -1; e = edge[e].next)
{
int v = edge[e].v, w = edge[e].w;
if(d[v] > d[x] + w)
{
d[v] = d[x] + w;
if(!inq[v])
{
inq[v] = 1;
q.push(v);
}
}
}
}
int ans = d[e];
if(ans == INF) printf("unreachable\n");
else printf("%d\n", ans);
}
void read_graph(int u, int v, int w)
{
edge[cnt].v = v, edge[cnt].w = w;
edge[cnt].next = first[u], first[u] = cnt++;
}
int main()
{
int T, times = 0;
scanf("%d", &T);
while(T--)
{
init();
scanf("%d%d%d%d", &n, &m, &s, &e);
while(m--)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
read_graph(u, v, w);
read_graph(v, u, w);
}
printf("Case #%d: ", ++times);
spfa(s);
}
return 0;
}