1. 程式人生 > >[BZOJ1003][ZJOI2006]物流運輸

[BZOJ1003][ZJOI2006]物流運輸

長度 for tle emp pop top str mem algo

這個題一開始沒有什麽思路,看了黃學長的blog,才發現這個題是個很暴力的DP,設\(f[i]\)為前\(i\)天的花費,\(dist[i][j]\)\([i,j]\)這幾天的最短路徑長度,則易得\(f[i] = min\{dist[1][i], f[j-1]+k+dist[j][i]\}\)。然後,dist數組竟然是暴力跑\(n^2\)遍最短路,復雜度\(O(n^2\cdot (m+n)logn)\),雖然看起來過不了,但是由於會有很多點被ban掉,而且也跑不滿,所以還是可以過掉的(再說時限10s怎麽著也不會TLE吧)。

code:

#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>

const int N = 25;
const int M = 110;
const int E = N*N;
const int INF = 1e9;
typedef long long LL;

LL dist[M][M], f[M];
int hd[N], to[E], nxt[E], w[E], cnt;
int ban[M][N];
int vis[N], dis[N];
int n, m, e, k;
struct node {
    int pos, w;
    node (int a = 0, int b = 0) : pos(a), w(b) {};
    bool operator < (const node &a) const {
        return w > a.w;
    }
};
std::priority_queue<node> q;

void adde(int x, int y, int z) {
    cnt++;
    to[cnt] = y;
    nxt[cnt] = hd[x];
    w[cnt] = z;
    hd[x] = cnt;
} 

int dij(int s, int t) {
    memset(vis, 0, sizeof vis);
    for (int i = 2; i <= m; ++i) dis[i] = INF;
    for (int i = s; i <= t; ++i) {
        for (int j = 2; j < m; ++j) {
            if (ban[i][j]) vis[j] = 1;
        }
    }
    q.push(node(1, 0));
    dis[1] = 0;
    node tmp;
    while (!q.empty()) {
        tmp = q.top(); q.pop();
        if (vis[tmp.pos]) continue;
        vis[tmp.pos] = 1;
        for (int i = hd[tmp.pos]; i; i = nxt[i]) if (!vis[to[i]]) {
            if (dis[to[i]] > tmp.w + w[i]) {
                dis[to[i]] = tmp.w + w[i];
                q.push(node(to[i], dis[to[i]]));
            }
        }
    }
    return dis[m];
}

int main() {
    scanf("%d%d%d%d", &n, &m, &k, &e);
    for (int i = 1, x, y, z; i <= e; ++i) {
        scanf("%d%d%d", &x, &y, &z);
        adde(x, y, z);
        adde(y, x, z);
    }
    int d;
    scanf("%d", &d);
    for (int i = 1, x, y, z; i <= d; ++i) {
        scanf("%d%d%d", &z, &x, &y);
        for (int j = x; j <= y; ++j) {
            ban[j][z] = 1; // mark
        }
    }
    for (int i = 1; i <= n; ++i) {
        for (int j = i; j <= n; ++j) {
            dist[i][j] = dij(i, j);
        }
    }
    f[0] = 0;
    for (int i = 1; i <= n; ++i) {
        f[i] = (LL)dist[1][i] * i;
        //printf("%d\n", f[i]);
        for (int j = 1; j <= i; ++j) {
            f[i] = std::min(f[i], f[j-1]+k+(LL)dist[j][i]*(i-j+1));
        }
    }
    printf("%lld\n", f[n]);
    return 0;
}

mark的那個地方我竟然寫成了ban[j][i],還是要更仔細。其實這個數據範圍是要開long long的,不過好像沒有刻意卡,但還是要註意。

[BZOJ1003][ZJOI2006]物流運輸