codevs 1021 玛丽卡

mac2022-06-30  21

题目描述 Description 麦克找了个新女朋友,玛丽卡对他非常恼火并伺机报复。因为她和他们不住在同一个城市,因此她开始准备她的长途旅行。 在这个国家中每两个城市之间最多只有一条路相通,并且我们知道从一个城市到另一个城市路上所需花费的时间。 麦克在车中无意中听到有一条路正在维修,并且那儿正堵车,但没听清楚到底是哪一条路。无论哪一条路正在维修,从玛丽卡所在的城市都能到达麦克所在的城市。玛丽卡将只从不堵车的路上通过,并且她将按最短路线行车。麦克希望知道在最糟糕的情况下玛丽卡到达他所在的城市需要多长时间,这样他就能保证他的女朋友离开该城市足够远。编写程序,帮助麦克找出玛丽卡按最短路线通过不堵车道路到达他所在城市所需的最长时间(用分钟表示)。

输入描述 Input Description 第一行有两个用空格隔开的数N和M,分别表示城市的数量以及城市间道路的数量。1≤N≤1000,1≤M≤N*(N-1)/2。城市用数字1至N标识,麦克在城市1中,玛丽卡在城市N中。

接下来的M行中每行包含三个用空格隔开的数A,B和V。其中1≤A,B≤N,1≤V≤1000。这些数字表示在A和城市B中间有一条双行道,并且在V分钟内是就能通过。

输出描述 Output Description 输出文件的第一行中写出用分钟表示的最长时间,在这段时间中,无论哪条路在堵车,玛丽卡应该能够到达麦克处,如果少于这个时间的话,则必定存在一条路,该条路一旦堵车,玛丽卡就不能够赶到麦克处。

样例输入 Sample Input

5 7 1 2 8 1 4 10 2 3 9 2 4 10 2 5 1 3 4 7 3 5 10

样例输出 Sample Output

#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; const int MAXN = 1000000, MAXE = 21474836; struct Edge { int from, to, cost; }es[MAXN]; int first[MAXN], nxt[MAXN], d[MAXN], n, m, tot = 1, pre[MAXN], h, ans; bool used[MAXN]; queue < int > q; void spfa(int s) { d[s] = 0; q.push(s); used[s] = 1; while(!q.empty()) { int u = q.front(); q.pop(); used[u] = 0; for(int i = first[u]; i != -1; i = nxt[i]) { int v = es[i].to; if(d[v] > d[u] + es[i].cost) { d[v] = d[u] + es[i].cost; if(!used[v]) { q.push(v); used[v] = 1; } if(h == 0) { pre[v] = i; } } } } } void build(int f, int t, int d) { es[++tot].cost = d; es[tot].from = f; es[tot].to = t; nxt[tot] = first[f]; first[f] = tot; } int main() { scanf("%d%d", &n, &m); memset(first, -1, sizeof(first)); for(int i = 1; i <= m; i++) { int v, a, b; scanf("%d%d%d", &a ,&b, &v); build(a, b, v); build(b, a, v); } for(int i = 1; i <= n; i++) d[i] = MAXE; spfa(1); h = 1; ans = d[n]; for(int i = pre[n]; pre[es[i].to]; i = pre[es[i].from]) { memset(used, 0, sizeof(used)); for(int j = 1; j <= n; j++) d[j] = MAXE; es[i].cost += MAXN; spfa(1); ans = max(ans, d[n]); es[i].cost -= MAXN; } printf("%d", ans); return 0; }

转载于:https://www.cnblogs.com/Loi-Vampire/p/6017059.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)