0%

51nod-1649-齐头并进

题目

在一个叫奥斯汀的城市,有n个小镇(从1到n编号),这些小镇通过m条双向火车铁轨相连。当然某些小镇之间也有公路相连。为了保证每两个小镇之间的人可以方便的相互访问,市长就在那些没有铁轨直接相连的小镇之间建造了公路。在两个直接通过公路或者铁路相连的小镇之间移动,要花费一个小时的时间。

现在有一辆火车和一辆汽车同时从小镇1出发。他们都要前往小镇n,但是他们中途不能同时停在同一个小镇(但是可以同时停在小镇n)。火车只能走铁路,汽车只能走公路。

现在请来为火车和汽车分别设计一条线路;所有的公路或者铁路可以被多次使用。使得火车和汽车尽可能快的到达小镇n。即要求他们中最后到达小镇n的时间要最短。输出这个最短时间。(最后火车和汽车可以同时到达小镇n,也可以先后到达。)

样例解释:

在样例中,火车可以按照 1⟶3⟶4 行驶,汽车 1⟶2⟶4 按照行驶,经过2小时后他们同时到过小镇4。

输入

单组测试数据。
第一行有两个整数n 和 m (2≤n≤400, 0≤m≤n*(n-1)/2) ,表示小镇的数目和铁轨的数目。
接下来m行,每行有两个整数u 和 v,表示u和v之间有一条铁路。(1≤u,v≤n, u≠v)。
输入中保证两个小镇之间最多有一条铁路直接相连。
输出
输出一个整数,表示答案,如果没有合法的路线规划,输出-1。
输入样例

1
2
3
4 2
1 3
3 4

输出样例

1
2

解法:

两次最短路取最大值即可。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<stdio.h>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<set>
using namespace std;
struct Node
{
int to;
long long len;
bool operator<(const Node &a) const
{
return len > a.len;
}
};
bool isUsed[510];
long long ans[510];
vector<Node> NodeQueue[510];
set<int> sto[510];
void addEdge(int s, int e, int len)
{
NodeQueue[s].push_back((Node){e,len});
NodeQueue[e].push_back((Node){s,len});
}
int n,m;
priority_queue<Node> PriNodeQueue;
long long len(int s, int t)
{
for(int i = 0; i < 505; i++)
ans[i] = 999999999999;
ans[s] = 0;
PriNodeQueue.push((Node){s,0});
while(!PriNodeQueue.empty()){
Node now = PriNodeQueue.top();
PriNodeQueue.pop();
int u = now.to;
if(!isUsed[u]){
isUsed[u] = true;
for(int i = 0; i < NodeQueue[u].size(); i++){
if(!isUsed[NodeQueue[u][i].to]){
int v = NodeQueue[u][i].to;
int len = NodeQueue[u][i].len;
if(ans[v] > ans[u] + len)
{
ans[v] = ans[u] + len;
PriNodeQueue.push((Node){v,ans[v]});
}
}
}
}
}
return ans[t];
}
int main()
{
scanf("%d%d", &n, &m);
while(m--)
{
int s, e, len;
scanf("%d%d",&s, &e);
sto[s].insert(e);
sto[e].insert(s);
addEdge(s, e, 1);
}
long long ans1 = len(1,n);
fill(isUsed, isUsed + 510, 0);
for(int i = 0; i < 510; i++)
NodeQueue[i].clear();
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(i != j && sto[i].find(j) == sto[i].end())
addEdge(i,j,1);

long long ans2 = len(1,n);
long long ans = max(ans1, ans2);
if(ans != 999999999999)
printf("%lld\n", ans);
else
{
printf("-1");
}

return 0;

}