【PAT甲级】1072. Gas Station (30)

此题用Dijkstra计算;如果用Floyd最后一个测试用例会超时
#include 
#include  
#include 
#include 
#include 
#include 
#define INF 1<<29
using namespace std;
struct T {
    int min;
    int sum;
    int index;
};
int min(int a, int b); 
T dij(int start);
bool cmp(T a, T b);

int n, m, k, ds;
int N;
int cost[1100][1100];

int main() {
    cin >> n >> m >> k >> ds;
    N = m + n;
    int p1, p2, d;
    string p1str, p2str;
    vector v;
    for (int i = 0; i <= N; i++) {
        for (int j = 0; j <= N; j++) {
            if (i == j) cost[i][j] = 0;
            else cost[i][j] = INF;
        }
    }
    for (int i = 0; i < k; i++) {
        cin >> p1str >> p2str >> d;
        if (p1str[0] == 'G') p1 = n + atoi(p1str.substr(1).c_str());
        else p1 = atoi(p1str.c_str());
        if (p2str[0] == 'G') p2 = n + atoi(p2str.substr(1).c_str());
        else p2 = atoi(p2str.c_str());
        cost[p1][p2] = cost[p2][p1] = d;
    }
    for (int i = n + 1; i <= N; i++) {
        T t = dij(i);
        if (t.min != -1) v.push_back(t);
    }
    sort(v.begin(), v.end(), cmp);
    if (v.size()) 
        printf("G%d\n%.1f %.1f\n", v[0].index - n, float(v[0].min), float(v[0].sum)/n);
    else 
        printf("No Solution");
    return 0;
}
int min(int a, int b) {
    return (a < b ? a : b);
}
bool cmp(T a, T b) {
    if (a.min > b.min) return true;
    else if (a.min == b.min && a.sum < b.sum) return true;
    else if (a.min == b.min && a.sum == b.sum && a.index < b.index) return true;
    else return false;
}
T dij(int start) {
    int *d = new int[N+1];
    int *used = new int[N+1];
    fill(d, d + N + 1, INF);
    fill(used, used + N + 1, 0);
    d[start] = 0;
    while (true) {
        int v = -1;
        for (int u = 1; u <= N; u++) {
            if (!used[u] && (v == -1 || d[u] < d[v]))
                v = u;
        }
        if (v == -1) break;
        used[v] = 1;
        for (int u = 1; u <= N; u++) {
            d[u] = min(d[u], d[v] + cost[v][u]);
        }
    }
    int min = INF;
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        if (d[i] < min) min = d[i];
        sum += d[i];
    }
    for (int i = 1; i <= n; i++) {
        if (d[i] > ds) min = -1;
    }
    T t;
    t.min = min;
    t.sum = sum;
    t.index = start;
    return t;
}

你可能感兴趣的:(PAT)