2018.07.20 bzoj1614: Telephone Lines架设电话线(二分+最短路)

时间:2021-10-08 08:56:09

传送门

这题直接做显然gg" role="presentation" style="position: relative;">gggg,看这数据范围也不可能是只跑一波最短路那么简单。

没错,这道题需要你跑很多次最短路。

没错,这是一道二分+最短路验证的题。

事实上,题目要求的东西已经提示了要使用二分。毕竟是求路径上第k+1" role="presentation" style="position: relative;">k+1k+1大条边的权值的最小值。所以这东西怎么二分判定?

干脆二分答案吧,二分路径上第k+1" role="presentation" style="position: relative;">k+1k+1大条边的权值的最小值是k" role="presentation" style="position: relative;">kk,然后怎么判定?

等等,这样的话不比k" role="presentation" style="position: relative;">kk大的边都没用了啊,也就是说,只有比k" role="presentation" style="position: relative;">kk大的边会影响答案,这样的话如果通过不超过题目数量限制的剩下的大边无法到达终点的话,显然k" role="presentation" style="position: relative;">kk取小了,不然的话可以继续将k" role="presentation" style="position: relative;">kk缩小。

因此算法流程就很明显了,对于二分出来的值v" role="presentation" style="position: relative;">vv,所有边中权值比v" role="presentation" style="position: relative;">vv大的真实边权为1,其它的边真实边权为0,然后在新图上跑最短路,跑出来如果最短路长度没有超出题目限制,就让v" role="presentation" style="position: relative;">vv减小,否则让v" role="presentation" style="position: relative;">vv增大。

代码如下:

#include<bits/stdc++.h>
#define N 1005
#define M 1000005
using namespace std;
inline int read(){
    int ans=0;
    char ch=getchar();
    while(!isdigit(ch))ch=getchar();
    while(isdigit(ch))ans=(ans<<3)+(ans<<1)+(ch^48),ch=getchar();
    return ans;
}
int cnt=0,n,p,k,first[N],d[N];
bool vis[N];
struct node{int u,v,w;}t[M];
struct Node{int v,next,w;}e[M];
struct heap{int u,d;};
inline bool operator<(heap a,heap b){return a.d>b.d;}
inline void add(int u,int v,int w){
    e[++cnt].v=v,e[cnt].w=w;
    e[cnt].next=first[u];
    first[u]=cnt;
}
inline bool dijkstra(){
    memset(vis,false,sizeof(vis));
    memset(d,0x3f3f3f3f,sizeof(d));
    priority_queue<heap>q;
    q.push((heap){1,0});
    d[1]=0;
    while(!q.empty()){
        heap x=q.top();
        q.pop();
        if(vis[x.u])continue;
        vis[x.u]=true;
        for(int i=first[x.u];i;i=e[i].next){
            int v=e[i].v;
            if(vis[v])continue;
            if(d[v]>d[x.u]+e[i].w){
                d[v]=d[x.u]+e[i].w;
                q.push((heap){v,d[v]});
            }
        }
    }
    return d[n]<=k;
}
inline bool check(int x){
    memset(e,0,sizeof(e)),cnt=0,memset(first,0,sizeof(first));
    for(int i=1;i<=p;++i){
        if(t[i].w<=x)add(t[i].u,t[i].v,0),add(t[i].v,t[i].u,0);
        else add(t[i].u,t[i].v,1),add(t[i].v,t[i].u,1);
    }
    return dijkstra();
}
int main(){
    int l=0,r=0;
    n=read(),p=read(),k=read();
    for(int i=1;i<=p;++i)t[i].u=read(),t[i].v=read(),r=max(r,t[i].w=read());
    if(!check(0x3f3f3f3f)){
        printf("-1");
        return 0;
    }
    while(l<=r){
        int mid=l+r>>1;
        if(check(mid))r=mid-1;
        else l=mid+1;
    }
    if(check(l))printf("%d",l);
    else printf("%d",r);
    return 0;
}