NWERC2016I

题目大意

给出一个度数最大为$10$的有向图,有些点上有两种之一的资源,求从出发点出发最少经过多少个点可以收集齐两种资源。

简要题解

和度数没啥关系。。bfs就好,我个智障用个蛋的dijkstra

#include <queue>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

using VI = vector<int>;
using LL = long long;

const int INF = 0x3f3f3f3f;
const int MAXN = 1e5 + 10;
const int MAXE = MAXN * 10;
struct Edge {
    int e, h[MAXN], to[MAXE], nxt[MAXE];
    Edge() {
        e = 0; memset(h, -1, sizeof h);
    }
    void addEdge(int u, int v) {
        to[e] = v, nxt[e] = h[u], h[u] = e++;
    }
} E, G;

struct Info {
    int u, d;
    Info(int u, int d) : u(u), d(d) {}
    bool operator<(const Info &rhs) const {
        return d > rhs.d;
    }
};

void getDist(Edge&e, VI&s, VI&d) {
    priority_queue<Info> q;
    fill(d.begin(), d.end(), INF);
    for (auto&&u : s) {
        d[u] = 0;
        q.push(Info(u, 0));
    }
    while (!q.empty()) {
        Info u = q.top(); q.pop();
        for (int i = e.h[u.u]; i != -1; i = e.nxt[i]) {
            int v = e.to[i];
            if (u.d + 1 < d[v]) {
                d[v] = u.d + 1;
                q.push(Info(v, d[v]));
            }
        }
    }
}

int main() {
#ifdef lol
    freopen("I.in", "r", stdin);
#endif

    int n, m, k; cin >> n >> m >> k;
    vector<int> s(1), o(m), c(k), d1(n), d2(n), d3(n);
    s[0] = 0;
    for (int i = 0; i < m; ++i) {
        cin >> o[i];
        --o[i];
    }
    for (int i = 0; i < k; ++i) {
        cin >> c[i];
        --c[i];
    }
    
    for (int i = 0; i < n; ++i) {
        int k, u; cin >> k;
        while (k--) {
            cin >> u; --u;
            E.addEdge(i, u);
            G.addEdge(u, i);
        }
    }

    getDist(E, s, d1);
    getDist(G, o, d2);
    getDist(G, c, d3);

    int ans = INF;
    for (int i = 0; i < n; ++i) {
        ans = (int)min((LL)ans, (LL)d1[i] + d2[i] + d3[i]);
    }
    if (ans == INF) {
        cout << "impossible" << endl;
    } else {
        cout << ans << endl;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/ichn/p/6792328.html