【二分+最短路】340. 通信线路

在郊区有 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;
}
 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值