[AcWing 903] 昂贵的聘礼

image
image
image

建图 + 有限制的最短路


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N = 1e6 + 10;
const int M = 100 + 10;
const int INF = 0x3f3f3f3f;

int n, m;
int h[N], e[N], ne[N], w[N], idx;
int d[M];
bool st[M];
int level[N];

void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx ++;
}

void dijkstra(int sp, int l, int r)
{
    memset(d, 0x3f, sizeof d);
    memset(st, false, sizeof st);
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, sp});
    d[sp] = 0;
    while (heap.size()) {
        auto t = heap.top();
        heap.pop();
        auto v = t.second;
        if (st[v])
            continue;
        st[v] = true;
        for (int i = h[v]; i != -1; i = ne[i]) {
            int j = e[i];
            if (level[j] < l || level[j] > r)
                continue;
            if (d[j] > d[v] + w[i]) {
                d[j] = d[v] + w[i];
                heap.push({d[j], j});
            }
        }
    }
}

void solve()
{
    cin >> m >> n;
    memset(h, -1, sizeof h);
    for (int i = 1; i <= n; i ++) {
        int price, cnt;
        cin >> price >> level[i] >> cnt;
        add(0, i, price);
        while (cnt --) {
            int id, cost;
            cin >> id >> cost;
            add(id, i, cost);
        }
    }
    int res = INF;
    for (int i = level[1] - m; i <= level[1]; i ++) {
        dijkstra(0, i, i + m);
        res = min(res, d[1]);
    }
    cout << res << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

  1. 可以假想一个虚拟源点作为起点,终点是 \(1\) 号点,\(dijkstra\) 的输入参数包括起点,等级下限,等级上限,可以枚举等级下限 \([level_1 - m, level_1]\),等级区间的长度为 \(m\),对应的等级上限为 \([level_1, level_1 + m]\),在 \(dijkstra\) 的过程中,所选的源点一定要满足等级在上限和下限之间,最后,结果取所有枚举情况下的最小值
posted @ 2022-08-09 19:35  wKingYu  阅读(32)  评论(0)    收藏  举报