Telephone Lines S
[USACO08JAN] Telephone Lines S
题目描述
Farmer John wants to set up a telephone line at his farm. Unfortunately, the phone company is uncooperative, so he needs to pay for some of the cables required to connect his farm to the phone system.
There are N (1 ≤ N ≤ 1,000) forlorn telephone poles conveniently numbered 1..N that are scattered around Farmer John's property; no cables connect any them. A total of P (1 ≤ P ≤ 10,000) pairs of poles can be connected by a cable; the rest are too far apart.
The i-th cable can connect the two distinct poles Ai and Bi, with length Li (1 ≤ Li ≤ 1,000,000) units if used. The input data set never names any {Ai, Bi} pair more than once. Pole 1 is already connected to the phone system, and pole N is at the farm. Poles 1 and N need to be connected by a path of cables; the rest of the poles might be used or might not be used.
As it turns out, the phone company is willing to provide Farmer John with K (0 ≤ K < N) lengths of cable for free. Beyond that he will have to pay a price equal to the length of the longest remaining cable he requires (each pair of poles is connected with a separate cable), or 0 if he does not need any additional cables.
Determine the minimum amount that Farmer John must pay.
多年以后,笨笨长大了,成为了电话线布置师。由于地震使得某市的电话线全部损坏,笨笨是负责接到震中市的负责人。该市周围分布着
第i对电线杆的两个端点分别是
电信公司决定支援灾区免费为此市连接
请你计算一下,将电话线引导震中市最少需要在电话线上花多少钱?
输入格式
输入文件的第一行包含三个数字
第二行到第
输出格式
一个整数,表示该项工程的最小支出,如果不可能完成则输出 -1
。
样例 #1
样例输入 #1
5 7 1
1 2 5
3 1 4
2 4 8
3 2 3
5 2 9
3 4 7
4 5 6
样例输出 #1
4
P1948 [USACO08JAN] Telephone Lines S
分析
要使
因此大于x的边的数量必须要小于k。
最小化最大值,考虑二分:
在区间
-
当存在
易证明, ,因此 。 -
当存在
, 。
因此二分确定区间,再取区间的最小值,当然是边权存在情况下的最小值,就可以得到答案。
二分区间为
具体来说:
对于一个满足
时,虽然满足 ,但一定不满足最小,舍去。 时,可能满足 ,此时答案 就更新为 。
对于一个满足
时,一定有 ,不符合条件,舍去。 时, ,可能满足 ,此时答案 就更新为 。
这就是二分的完整过程。
tips
为何二分区间为 ?
- 对于左端点
,当从 到 的路径经过的边的数量小于 答案就是 。 - 对于右端点
, 无法到达 时, 作为无解的返回值。
如何求 ?
如果边长大于
接下来求从
code
#include <bits/stdc++.h>
using namespace std;
const int N=1005,M=2e5+5;
int n,m,k;
int h[N],e[M],w[M],ne[M],tot;
deque<int> q;
int dis[N];
bool vis[N];
void add(int x,int y,int z)
{
e[++tot]=y,w[tot]=z,ne[tot]=h[x],h[x]=tot;
}
bool check(int x)
{
memset(dis,0x3f,sizeof dis);
memset(vis,0,sizeof vis);
dis[1]=0;
q.push_back(1);
while(q.size())
{
int u=q.front();q.pop_front();
if(vis[u]) continue;
vis[u]=1;
for(int i=h[u];i;i=ne[i])
{
int y=e[i],z=w[i]>x;
if(dis[y]>dis[u]+z)
{
dis[y]=dis[u]+z;
if(z) q.push_back(y);
else q.push_front(y);
}
}
}
return dis[n]<=k;
}
int main ()
{
cin>>n>>m>>k;
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
add(x,y,z),add(y,x,z);
}
int l=0,r=1e6+1;
while(l<r)
{
int mid=(l+r)>>1;
if(check(mid)) r=mid;
else l=mid+1;
}
if(r==1e6+1) r=-1;
cout<<r<<"\n";
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」