题解 P3659 【[USACO17FEB]Why Did the Cow Cross the Road I G】

· · 题解

更好的阅读体验请戳这里。

十分裸的最短路。

设f[i][j][0/1/2] 表示到点(i,j)

走的步数%3等于0/1/2的最短路。

然后没了...

#include <iostream>
#include <cstdio> 
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
#define reg register
inline char gc() {
    static const int bs = 1 << 22;
    static unsigned char buf[bs], *st, *ed;
    if (st == ed) ed = buf + fread(st = buf, 1, bs, stdin);
    return st == ed ? EOF : *st++;
}
#define gc getchar
inline int read() {
    int res=0;char ch=gc();bool fu=0;
    while(!isdigit(ch))fu|=(ch=='-'), ch=gc();
    while(isdigit(ch))res=(res<<3)+(res<<1)+(ch^48), ch=gc();
    return fu?-res:res;
}
#define N 100005
int n, T;
int mp[105][105];
int dis[105][105][3];
bool ex[105][105][3];
int dx[] = {0, 1, -1, 0, 0}, dy[] = {0, 0, 0, 1, -1};

struct date {
    int x, y, lim;
};

inline void spfa()
{
    memset(dis, 0x3f, sizeof dis);
    dis[1][1][0] = 0;
    queue <date> q;
    q.push((date){1, 1, 0});
    while(!q.empty())
    {
        int x = q.front().x, y = q.front().y, lim = q.front().lim;
        q.pop();
        ex[x][y][lim] = 0;
        for (reg int i = 1 ; i <= 4 ; i ++)
        {
            int tx = x + dx[i], ty = y + dy[i];
            if (tx <= 0 or tx > n or ty <= 0 or ty > n) continue;
            int nt = (lim + 1) % 3;
            if (dis[tx][ty][nt] > dis[x][y][lim] + T + (nt == 0) * mp[tx][ty]) {
                dis[tx][ty][nt] = dis[x][y][lim] + T + (nt == 0) * mp[tx][ty];
                if (!ex[tx][ty][nt]) ex[tx][ty][nt] = 1, q.push((date){tx, ty, nt});
            }
        }
    }
}

int main()
{
    n = read(), T = read();
    for (reg int i = 1 ; i <= n ; i ++) 
        for (reg int j = 1 ; j <= n ; j ++)
            mp[i][j] = read();
    spfa();
    printf("%d\n", min(dis[n][n][0], min(dis[n][n][1], dis[n][n][2])));
    return 0;
}