后5个TLE求解

P2895 [USACO08FEB] Meteor Shower S

CuteGhost @ 2023-03-20 18:04:09

package com.tao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.*;

public class MSS {
    static int n;
    static int[][] ruin = new int[330][330];
    static int[] dx = {-1, 0, 1, 0};
    static int[] dy = {0, 1, 0, -1};
    static int cnt = 0x3f3f3f3f;
    static boolean[][] st = new boolean[330][330];
    public static void main(String[] args) throws IOException {
        for (int[] ints : ruin) {
            Arrays.fill(ints,0x3f3f3f3f);
        }
        StreamTokenizer sr = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        sr.nextToken();
        n = (int) sr.nval;
        for (int i = 0; i < n; i++) {
            int a, b, time;
            sr.nextToken();
            a = (int) sr.nval + 1;
            sr.nextToken();
            b = (int) sr.nval + 1;
            sr.nextToken();
            time = (int) sr.nval;
            ruin[a][b] = Math.min(ruin[a][b], time);
            ruin[a-1][b] = Math.min(ruin[a-1][b], time);
            ruin[a][b-1] = Math.min(ruin[a][b-1], time);
            ruin[a+1][b] = Math.min(ruin[a+1][b], time);
            ruin[a][b+1] = Math.min(ruin[a][b+1], time);
        }
        dfs(1, 1, 0);
        if(cnt<0x3f3f3f3f){
            System.out.println(cnt);
        }else System.out.println(-1);
    }

    static void dfs(int x, int y, int day) {
//        System.out.println(x+" "+y);
        if(day>cnt) return;
        if(ruin[x][y]>=0x3f3f3f3f){
            cnt = Math.min(cnt,day);
            return;
        }
        else if(ruin[x][y] <= day){
            return;
        }
        st[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx>=1 && ny>=1 && !st[nx][ny]){
                dfs(nx,ny,day+1);
            }
        }
        st[x][y] = false;
    }
}

by CuteGhost @ 2023-03-20 18:05:08

st数组我在尝试各种位置、放与不放结果是一样的。


|