跳到正文

题解

Telephone Lines S

wanghaoran000约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年7月15日
收录
2026年7月15日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前

题意
给出共有n个点,p条边的无向图,要求从点1到点n寻找一条路径,可以令路径上k条边免费,其他都要付费。总费用为该路径上需要付费的最大值,求最小总费用。
思路
先用二分算出价格上限x,用标记数组记录>x的边记为付费,其余记为不付费。将每一个x跑最短路,当最大值都无法到达n时,输出-1。
代码

C++
#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
const int INF = 0x3f3f3f3f;
struct Edge
{
    int v,w;
};
int n,p,k;
vector<Edge> g[N];
int dist[N];
bool vis[N];
bool check(int limit)
{
    memset(dist,0x3f,sizeof(dist));
    memset(vis,0,sizeof(vis));
    queue<int> q;
    dist[1]=0;
    q.push(1);
    vis[1]=true;

    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        vis[u]=false;

        for(auto &e:g[u])
        {
            int v=e.v;
            int w=(e.w>limit)?1:0;
            if(dist[v]>dist[u]+w)
            {
                dist[v]=dist[u]+w;
                if(!vis[v])
                {
                    vis[v]=true;
                    q.push(v);
                }
            }
        }
    }
    return dist[n]<=k;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin>>n>>p>>k;
    int mx=0;
    for(int i=1;i<=p;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        g[u].push_back({v,w});
        g[v].push_back({u,w});
        mx=max(mx,w);
    }

    if(!check(mx))
    {
        cout<<-1<<'\n';
        return 0;
    }
    int l=0,r=mx,ans=-1;
    while(l<=r)
    {
        int mid=(l+r)/2;
        if(check(mid))
        {
            ans=mid;
            r=mid-1;
        }
        else
        {
            l=mid+1;
        }
    }
    cout<<ans<<'\n';
    return 0;
}
原文