POJ3662 Telephone Lines 二分+最短路

来源:互联网 发布:js事件三个阶段 编辑:程序博客网 时间:2024/05/24 05:11

 

Telephone Lines
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 3468 Accepted: 1245

Description

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 ofP (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 andBi, with lengthLi (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 andN 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.

Input

* Line 1: Three space-separated integers: N, P, and K
* Lines 2..P+1: Line i+1 contains the three space-separated integers:Ai,Bi, and Li

Output

* Line 1: A single integer, the minimum amount Farmer John can pay. If it is impossible to connect the farm to the phone company, print -1.

Sample Input

5 7 11 2 53 1 42 4 83 2 35 2 93 4 74 5 6

Sample Output

4

Source

USACO 2008 January Silver
 
 
二分+最短路
题意:求一条路径从1到n使第k+1大的边最小。
二分答案mid,当原边权小于等于mid新边权为0,否则新边权为1.
求最短路,若小于等于k说明满足条件。
代码:
#include<cstdio>#include<cstring>#define N 1005int n,m,k,num,adj[N],low[N],f[N],q[N];struct edge{int v,w,c,pre;}e[N*20];void insert(int u,int v,int w){e[num].v=v;e[num].c=w;e[num].pre=adj[u];adj[u]=num++;}int spfa(int x){int i,v,head=0,tail=0;memset(f,0,sizeof(f));memset(low,0x7f,sizeof(low));low[x]=0;q[++tail]=x;while(head!=tail){x=q[head=(head+1)%N];f[x]=0;for(i=adj[x];~i;i=e[i].pre)if(low[v=e[i].v]>low[x]+e[i].w){low[v]=low[x]+e[i].w;if(!f[v]){f[v]=1;q[tail=(tail+1)%N]=v;}}}return low[n]<=k;}int ok(int x){int i,j;for(i=1;i<=n;i++)for(j=adj[i];~j;j=e[j].pre)if(e[j].c<=x)e[j].w=0;elsee[j].w=1;return spfa(1);}int main(){int u,v,w;while(~scanf("%d%d%d",&n,&m,&k)){num=0;memset(adj,-1,sizeof(adj));int l=0,r=0,mid,ans=-1;while(m--){scanf("%d%d%d",&u,&v,&w);insert(u,v,w);insert(v,u,w);if(w>r)r=w;}while(l<=r){mid=(l+r)/2;if(ok(mid)){ans=mid;r=mid-1;}elsel=mid+1;}printf("%d\n",ans);}}