LightOJ - 1281 New Traffic System(二维最短路)

题目大意:给你N个点,M条已有的边,K条可以添加的边,K条中最多只能选择D条,问0到N-1的最短路

解题思路:二维最短路,多开一维存储走到该点已经选择了多少条边了

#include 
#include 
#include 
#include 
using namespace std;
const int N = 10010;
const int M = 30010;
const int INF = 0x3f3f3f3f;

struct Edge{
    int u, v, mark, dis, next;
    Edge() {}
    Edge(int u, int v, int mark, int dis, int next): u(u), v(v), mark(mark), dis(dis), next(next){}
}E[M];

struct Node {
    int u, dis, times;
    Node() {}
    Node(int u, int dis, int times): u(u), dis(dis), times(times) {}
    bool operator < (const Node &a) const {
        return dis > a.dis;
    }
};

int head[N], d[N][12];
int n, m, k, t, cas = 1;
bool vis[N][12];

void init() {
    memset(head, -1, sizeof(head));
    scanf("%d%d%d%d", &n, &m, &k, &t);
    int u, v, dis;
    for (int i = 0; i < m; i++) {
        scanf("%d%d%d", &u, &v, &dis);
        E[i] = Edge(u, v, 0, dis, head[u]);
        head[u] = i;
    }

    for (int i = 0; i < k; i++) {
        scanf("%d%d%d", &u, &v, &dis);
        E[i + m] =  Edge(u, v, 1, dis, head[u]);
        head[u] = i + m;
    }
}

void solve() {
    priority_queue Q;
    memset(d, 0x3f, sizeof(d));
    memset(vis, 0 ,sizeof(vis));
    d[0][0] = 0;
    Q.push(Node(0, 0, 0));
    while (!Q.empty()) {
        int u = Q.top().u;
        int dis = Q.top().dis;
        int times = Q.top().times;
        Q.pop();
        if (vis[u][times]) continue;
        vis[u][times] = true;

        for (int i = head[u]; ~i; i = E[i].next) {
            int v = E[i].v;
            if (times + E[i].mark > t) continue;
            if (d[v][times + E[i].mark] > d[u][times] + E[i].dis) {
                d[v][times + E[i].mark] = d[u][times] + E[i].dis;
                Q.push(Node(v, d[v][times + E[i].mark], times + E[i].mark));
            }
        }
    }
    int ans = INF;
    for (int i = 0; i <= t; i++)
        ans = min(d[n - 1][i], ans);
    if (ans == INF) printf("Case %d: Impossible\n", cas++);
    else printf("Case %d: %d\n", cas++, ans);
}

int main() {
    int test;
    scanf("%d", &test);
    while (test--) {
        init();
        solve();
    }
    return 0;
}

你可能感兴趣的:(ACM-图论-最短路)