在郊区有 N 座通信基站,P 条双向电缆,第 i 条电缆连接基站AiAi和BiBi。
特别地,1 号基站是通信公司的总站,N 号基站位于一座农场中。
现在,农场主希望对通信线路进行升级,其中升级第 i 条电缆需要花费LiLi。
电话公司正在举行优惠活动。
农产主可以指定一条从 1 号基站到 N 号基站的路径,并指定路径上不超过 K 条电缆,由电话公司免费提供升级服务。
农场主只需要支付在该路径上剩余的电缆中,升级价格最贵的那条电缆的花费即可。
求至少用多少钱可以完成升级。
输入格式
第1行:三个整数N,P,K。
第2..P+1行:第 i+1 行包含三个整数Ai,Bi,LiAi,Bi,Li。
输出格式
包含一个整数表示最少花费。
数据范围
0≤K<N≤10000≤K<N≤1000,
1≤P≤100001≤P≤10000,
1≤Li≤10000001≤Li≤1000000
输入样例:
5 7 1
1 2 5
3 1 4
2 4 8
3 2 3
5 2 9
3 4 7
4 5 6
输出样例:
4
因为答案具有单调性,所以可以用二分答案,至此,问题就转换为了:是否存在一种合法的升级方案,使得花销不超过mid
所以在每次跑最短路的时候,将大于mid的边设为1,小于mid的边变为0,看到n点的最短路是否大于K即可,还有就是,此题有无法到达的情况,题中没说,记得判断并输出-1
此题还有DP解法,就先不介绍了
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
//typedef __int128 bll;
#define gcd __gcd
const ll maxn = 1e3+100;
const ll mod = 1e9+7;
//const ld pi = acos(-1.0);
const ll inf = 1e18;
//const ld eps = 1e-5;
//const ld e = exp(1);
ll n,p,k,l = inf,r = -inf,ans[maxn];
vector< pair<ll,ll> >G[maxn];
bool flag[maxn];
struct Why
{
ll now,step;
Why(ll a,ll b)
{
now = a;
step = b;
}
bool operator < (const Why a) const
{
return step > a.step;
}
};
void dij(ll x)
{
memset(flag,0,sizeof(flag));
for(ll i = 1; i <= n; i++)
ans[i] = inf;
ans[1] = 0;
priority_queue<Why>Q;
Q.push( Why(1,0) );
while(!Q.empty())
{
Why tmp = Q.top();
Q.pop();
ans[tmp.now] = min(ans[tmp.now],tmp.step);
if(flag[ tmp.now ] == 0)
{
flag[tmp.now] = 1;
for(ll i = 0; i < G[tmp.now].size(); i++)
{
ll to = G[tmp.now][i].first,val = G[tmp.now][i].second;
if(val < x)
Q.push( Why(to,tmp.step+0) );
else
Q.push(Why(to,tmp.step+1) );
}
}
}
return ;
}
bool check(ll x)
{
dij(x);
//cout << ans[n] << endl;
if(ans[n] <= k)
return true;
else
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> n >> p >> k;
for(ll i = 1; i <= p; i++)
{
ll x,y,z;
cin >> x >> y >> z;
G[x].push_back( make_pair(y,z) );
G[y].push_back( make_pair(x,z) );
l = min(l,z);
r = max(r,z);
}
dij(r);
//cout << ans[n] << endl;
if(ans[n] == inf)
{
cout << -1 << endl;
return 0;
}
while(l <= r)
{
ll mid = (l+r)/2;
if( check(mid) )
r = mid-1;
else
l = mid+1;
}
cout << l-1 << endl;
return 0;
}