【Codeforces 1063B】Labyrinth
阿新 • • 發佈:2019-03-02
off writer rst empty isempty poll nth run buffer
【鏈接】 我是鏈接,點我呀:)
【題意】
你可以往左最多x次,往右最多y次
問你從x,y出發最多能到達多少個格子
只能往上下左右四個方向走到沒有障礙的格子
【題解】
假設我們從(r,c)出發想要到固定某個點(i,j)的最短距離
我們設x0為向左走動的次數,y0為向右走動的次數
顯然(j-c)=y0-x0
即y0 = (j-c) + x0
這裏j-c是一個常數
也就是說當我們讓x0最小的時候到達每一個點的對應的y0也一定是最優的,因為和x0成正相關
因此我們只要求出來(r,c)到所有點所用的x0的最小值就好了
會發現沒個點到達相鄰的點的花費要麽就是1(往左走),要麽就是0(往其他方向走)
符合01bfs的特點
(01bfs:如果向左走的話,那麽就把新得到的狀態加入到末尾,否則加入到隊頭,因為花費為0的話,和之前的dis值相同,依然是當前所有的情況裏最低花費
(所以可以用來繼續更新最小值,因此是放在隊頭,這樣的話能始終維持隊列從頭到尾的dis值依次遞增的順序
(因此能保證每次嘗試用來更新的狀態都是當前狀況下最優的狀態,不會造成錯解或者漏解
【代碼】
import java.io.*; import java.util.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) throws IOException{ //InputStream ins = new FileInputStream("E:\\rush.txt"); InputStream ins = System.in; in = new InputReader(ins); out = new PrintWriter(System.out); //code start from here new Task().solve(in, out); out.close(); } static class Pair{ int x,y,d; public Pair(int x,int y,int d){ this.x = x; this.y = y; this.d = d; } } static int N = 2000; static class Task{ int n,m,r,c,x,y; String s[]; int dis[][]; int dx[]= {0,0,1,-1},dy[]= {1,-1,0,0}; Deque<Pair> queue; public void solve(InputReader in,PrintWriter out) { queue = new LinkedList<Pair>(); dis = new int[N+10][N+10]; s = new String[N+10]; n = in.nextInt();m = in.nextInt(); r = in.nextInt();c = in.nextInt(); x = in.nextInt();y = in.nextInt(); for (int i = 1;i <= n;i++) { s[i] = in.next(); StringBuilder sb = new StringBuilder(s[i]); sb.insert(0, ' '); s[i] = sb.toString(); } for (int i = 1;i <= N;i++) for (int j = 1;j <= N;j++) dis[i][j] = -1; dis[r][c] = 0; queue.offerFirst(new Pair(r,c,0)); while (!queue.isEmpty()) { Pair temp = queue.pollFirst(); int x0 = temp.x,y0 = temp.y,d = temp.d; for (int i = 0;i < 4;i++) { int x1 = x0 + dx[i];int y1 = y0 + dy[i]; int td = d; if (i==1) td++; if (x1>=1 && x1<=n && y1>=1 && y1<=m && s[x1].charAt(y1)!='*') { if (dis[x1][y1]==-1 ||dis[x1][y1]>td) { dis[x1][y1] = td; if (i==1) { queue.offerLast(new Pair(x1,y1,td)); }else { queue.offerFirst(new Pair(x1,y1,td)); } } } } } int ans = 0; for (int i = 1;i <= n;i++) for (int j = 1;j <= m;j++) { if (dis[i][j]==-1) continue; int x0 = dis[i][j]; int y0 = j-c + x0; if (x0<=x && y0<=y) { ans++; } } out.println(ans); } } static class InputReader{ public BufferedReader br; public StringTokenizer tokenizer; public InputReader(InputStream ins) { br = new BufferedReader(new InputStreamReader(ins)); tokenizer = null; } public String next(){ while (tokenizer==null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); }catch(IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
【Codeforces 1063B】Labyrinth