P2895

P2895 [USACO08FEB] Meteor Shower S

qiushunyuan2011 @ 2024-07-26 21:15:38

#include <bits/stdc++.h>

using namespace std;

int m;
struct nada {
    bool num;
    int t;
} a[305][305];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int mn = 1e9;

struct node {
    int t, x, y;
};
int main() {
    ios::sync_with_stdio(0);
    cin >> m;
    for (int i = 0; i <= 300; i++) {
        for (int j = 0; j <= 300; j++) {
            a[i][j].t = 1e9;
        }
    }
    for (int i = 1; i <= m; i++) {
        int x, y, t;
        cin >> x >> y >> t;
        if ((!a[x][y].num || a[x][y].t > t)) {
            a[x][y].num = 1;
            a[x][y].t = t;
        }
        if (x + 1 >= 0 && (!a[x + 1][y].num || a[x + 1][y].t > t)) {
            a[x + 1][y].num = 1;
            a[x + 1][y].t = t;
        }
        if (x - 1 >= 0 && (!a[x - 1][y].num || a[x - 1][y].t > t)) {
            a[x - 1][y].num = 1;
            a[x - 1][y].t = t;
        }
        if (y + 1 >= 0 && (!a[x][y + 1].num || a[x][y + 1].t > t)) {
            a[x][y + 1].num = 1;
            a[x][y + 1].t = t;
        }
        if (y - 1 >= 0 && (!a[x][y - 1].num || a[x][y - 1].t > t)) {
            a[x][y - 1].num = 1;
            a[x][y - 1].t = t;
        }
    }
    queue<node> q;
    q.push({0, 0, 0});
    while (!q.empty()) {
        int t = q.front().t;
        int x = q.front().x;
        int y = q.front().y;
        if (!a[x][y].num) {
            mn = min(mn, t);
            break;
        }
        q.pop();
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if (nx >= 0 && ny >= 0) {
                if (a[nx][ny].num) {
                    if (a[nx][ny].t > t + 1) {
                        q.push({t + 1, nx, ny});
                    }
                } else {
                    q.push({t + 1, nx, ny});
                }
            }
        }
    }
    if (mn == 1e9) {
        cout << "-1";
    } else {
        cout << mn;
    }
    return 0;
}

为什么10-13个点MLE,14个点TLE


by zhuozhiyuan @ 2024-07-27 19:07:07

判断不走回头路更佳


|