在一个叫奥斯汀的城市,有n个小镇(从1到n编号),这些小镇通过m条双向火车铁轨相连。当然某些小镇之间也有公路相连。为了保证每两个小镇之间的人可以方便的相互访问,市长就在那些没有铁轨直接相连的小镇之间建造了公路。在两个直接通过公路或者铁路相连的小镇之间移动,要花费一个小时的时间。
现在有一辆火车和一辆汽车同时从小镇1出发。他们都要前往小镇n,但是他们中途不能同时停在同一个小镇(但是可以同时停在小镇n)。火车只能走铁路,汽车只能走公路。
现在请来为火车和汽车分别设计一条线路;所有的公路或者铁路可以被多次使用。使得火车和汽车尽可能快的到达小镇n。即要求他们中最后到达小镇n的时间要最短。输出这个最短时间。(最后火车和汽车可以同时到达小镇n,也可以先后到达。)
样例解释:
在样例中,火车可以按照 1⟶3⟶4 行驶,汽车 1⟶2⟶4 按照行驶,经过2小时后他们同时到过小镇4。
Input
单组测试数据。 第一行有两个整数n 和 m (2≤n≤400, 0≤m≤n*(n-1)/2) ,表示小镇的数目和铁轨的数目。 接下来m行,每行有两个整数u 和 v,表示u和v之间有一条铁路。(1≤u,v≤n, u≠v)。 输入中保证两个小镇之间最多有一条铁路直接相连。
Output
输出一个整数,表示答案,如果没有合法的路线规划,输出-1。
Input示例
4 2 1 3 3 4
Output示例
2
思路 :蛮水的题。。。两遍最短路取最大值即可
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
//#pragma GCC optimize(2)
using namespace std;
#define maxn 405
#define inf 1e18
//#define mod 1e9+7
typedef long long ll;
const ll mod = 1e9+7;
ll n,m,ans1 = inf,ans2 = inf;
vector<ll>A[maxn],B[maxn];
bool flag[maxn][maxn],r[maxn];
struct Why
{
ll now,dis;
Why(ll a,ll b)
{
now = a;
dis = b;
}
bool operator < (const Why t) const
{
return dis > t.dis;
}
};
void slove1()
{
priority_queue<Why>AA;
AA.push(Why(1,0));
while(!AA.empty())
{
Why temp = AA.top();
AA.pop();
if(r[temp.now] == 0)
{
r[temp.now] = 1;
if(temp.now == n)
{
ans1 = min(ans1,temp.dis);
}
for(ll i = 0; i < A[temp.now].size(); i++)
{
AA.push( Why(A[temp.now][i],temp.dis+1) );
}
}
}
}
void slove2()
{
priority_queue<Why>AA;
AA.push(Why(1,0));
while(!AA.empty())
{
Why temp = AA.top();
AA.pop();
if(r[temp.now] == 0)
{
r[temp.now] = 1;
if(temp.now == n)
{
ans2 = min(ans2,temp.dis);
}
for(ll i = 0; i < B[temp.now].size(); i++)
{
AA.push( Why(B[temp.now][i],temp.dis+1) );
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin >> n >> m;
while(m--)
{
ll a,b;
cin >> a >> b;
A[a].push_back(b);
A[b].push_back(a);
flag[a][b] = 1;
flag[b][a] = 1;
}
for(ll i = 1; i <= n; i++)
{
for(ll j = i+1; j <= n; j++)
{
if(flag[i][j] == 0)
{
B[i].push_back(j);
B[j].push_back(i);
}
}
}
slove1();
memset(r,0,sizeof(r));
slove2();
if(ans1 == inf || ans2 == inf)
cout << -1 <<endl;
else
cout << max(ans1,ans2) << endl;
return 0;
}