POJ - 3662 Telephone Lines 最短路二分+雙端隊列優化

題目描述

給定一個圖, 可以選着一個1 -> n的路線, 然後可以把這條路上的k個邊免費, 然後支付免費後最貴的一條邊, 求支付的這條邊最小是多少

樣例

Sample Input
5 7 1
1 2 5
3 1 4
2 4 8
3 2 3
5 2 9
3 4 7
4 5 6
Sample Output
4

思路

  • 二分答案, l = 0, r = 1e6+1
  • 因爲結果可能是0的, 所以左邊界是0, 因爲可能存在無解的情況, 所以有邊界是1e6+1
  • 然後我們把二分答案, 把邊權大於答案的設爲1, 小於的設爲0, dis[n]裏面存的就是從1到n大於答案的數量, 我們找到大於答案的數量最多(k)的答案就是最後的結果
  • 由於邊權只有0和1, 所以我們用到雙端隊列優化
#include <iostream>
#include <cstring>
#include <algorithm>
#include <deque>

using namespace std;

const int N = 20010;

int e[N], w[N], ne[N], h[1010], len;
int n, m, k;
bool vis[1010];
int dis[1010];
void add(int a, int b, int c)
{
    e[len] = b;
    w[len] = c;
    ne[len] = h[a];
    h[a] = len++;
}

bool check(int bound)
{
    memset(vis, false, sizeof vis);
    memset(dis, 0x3f, sizeof dis);
    dis[1] = 0;
    deque<int> q;
    q.push_back(1);
    while(q.size())
    {
        int x = q.front();
        q.pop_front();
        if(vis[x]) continue;
        vis[x] = true;
        for(int i = h[x]; ~i; i = ne[i])
        {
            int y = e[i];
            int c = w[i] > bound;
            if(dis[y] > dis[x] + c)
            {
                dis[y] = dis[x] + c;
                if(c == 0)
                    q.push_front(y);
                else q.push_back(y);
            }
        }
    }
   
    return dis[n] <= k;
}

int main()
{
    cin >> n >> m >> k;
    memset(h, -1, sizeof h);
    for(int i = 1; i<= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }
    
    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)
        cout << -1 << endl;
    else 
        cout << r << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章