(图论)追债之旅

追债之旅

\(最短路 + dp\)

思路

\(这里用了拆点,即每个点并不只是位置,而是位置+到达的天数\)

\(dis[i][j]:表示第i天到达j的最小花费\)

\(dist[day][to]=min(dist[day][to],dist[day-1][now]+w[i]+cosy[day])\)

\(由于拆点,我们需要重载一个Node\)

代码
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1010, M = 1e4 + 10; 
int h[N], ne[M], e[M], w[M], idx;
bool st[15][N];
int dist[15][N];
int a[15];
int n, m, k;

void add(int a, int b, int c) {
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
 
struct Node {
    int day, pos, dis;
    Node(int _day, int _pos, int _dis) : day(_day), pos(_pos), dis(_dis) {}
    bool operator < (const Node & t) const {
        return dis > t.dis;
    }
};

void dijkstra() {
    memset(dist, 0x3f, sizeof dist);
    memset(st, 0, sizeof st);
    dist[0][1] = 0;
    priority_queue<Node> q;
    q.push(Node(0, 1, 0));
    while (q.size()) {
        auto t = q.top();
        q.pop();
        int day = t.day, pos = t.pos, dis = t.dis;
        if (st[day][pos]) continue;
        st[day][pos] = true;
        for (int i = h[pos]; ~i; i = ne[i]) {
            if (day + 1 > k) continue;
            int j = e[i];
            if (dist[day + 1][j] > dis + a[day + 1] + w[i]) {
                dist[day + 1][j] = dis + a[day + 1] + w[i];
                q.push(Node(day + 1, j, dist[day + 1][j]));
            }
        }
    }
}

int main() {
    IO;
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    memset(h, -1, sizeof h); 
    cin >> n >> m >> k;
    while (m--) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c), add(b, a, c);
    }
    for (int i = 1; i <= k; ++i) cin >> a[i]; 
    dijkstra();
    int ans = inf;
    for (int i = 1; i <= k; ++i) ans = min(ans, dist[i][n]);
    if (ans == inf) cout << "-1\n";
    else cout << ans << '\n';
}


posted @ 2021-03-01 16:26  phr2000  阅读(61)  评论(0编辑  收藏  举报