题意:给定一个起点和终点,问最短路径
思路:最短路径测试模板题...
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 20005
#define LL long long
int cas=1,T;
int n,m,w;
const int INF = 1<<29;
struct Edge
{
int from,to,dist;
Edge(int u,int v,int d):from(u),to(v),dist(d){}
};
struct Bellman_ford
{
vector<Edge>edges;
vector<int> G[maxn];
int d[maxn];
int inq[maxn];
int cnt[maxn];
void init()
{
for (int i = 0;i<=n;i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int dist)
{
edges.push_back(Edge(from,to,dist));
int mm = edges.size();
G[from].push_back(mm-1);
}
bool bellman_ford(int s)
{
queue<int>q;
memset(inq,0,sizeof(inq));
memset(cnt,0,sizeof(cnt));
for (int i =0;i<=n;i++)
d[i]=INF;
d[s]=0;
inq[s]=1;
q.push(s);
while (!q.empty())
{
int u = q.front();q.pop();
inq[u] = false;
for (int i =0;i<G[u].size();i++)
{
Edge &e = edges[G[u][i]];
if (d[u]<INF && d[e.to]>d[u]+e.dist)
{
d[e.to] = d[u] + e.dist;
if (!inq[e.to])
{
q.push(e.to);
inq[e.to]=1;
if (++cnt[e.to]>n)
return false;
}
}
}
}
return true;
}
};
int main()
{
//freopen("in","r",stdin);
scanf("%d",&T);
while (T--)
{
int s,e;
scanf("%d%d%d%d",&n,&m,&s,&e);
Bellman_ford bf;
bf.init();
for (int i = 0;i<m;i++)
{
int u,v,t;
scanf("%d%d%d",&u,&v,&t);
bf.AddEdge(u,v,t);
bf.AddEdge(v,u,t);
}
bf.bellman_ford(s);
if (bf.d[e] ==INF)
printf("Case #%d: unreachable\n",cas++);
else
printf("Case #%d: %d\n",cas++,bf.d[e]);
}
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}
题目
“A new internet watchdog is creating a stir inSpringfield. Mr. X, if that is his real name, hascome up with a sensational scoop.”Kent BrockmanThere are n SMTP servers connected by network cables. Each of the m cables connects two computersand has a certain latency measured in milliseconds required to send an email message. Whatis the shortest time required to send a message from server S to server T along a sequence of cables?Assume that there is no delay incurred at any of the servers.
Input
The first line of input gives the number of cases, N. N test cases follow. Each one starts with a linecontaining n (2 ≤ n ≤ 20000), m (0 ≤ m ≤ 50000), S (0 ≤ S < n) and T (0 ≤ T < n). S ̸= T. Thenext m lines will each contain 3 integers: 2 different servers (in the range [0, n − 1]) that are connectedby a bidirectional cable and the latency, w, along this cable (0 ≤ w ≤ 10000).
Output
For each test case, output the line ‘Case #x:’ followed by the number of milliseconds required to senda message from S to T. Print ‘unreachable’ if there is no route from S to T.
Sample Input
32 1 0 10 1 1003 3 2 00 1 1000 2 2001 2 502 0 0 1
Sample Output
Case #1: 100
Case #2: 150
Case #3: unreachable