[DFS] NOIP2017PJ board

Meaning of the questions: a m * m board, above n points, each point has its own color, the rest of the points are colorless. What is the minimum requirement from (1,1) to (m, m) cost? Which spanned two points if the color does not take the same, if a different color is required. 1 ¥, if cast membrane effect - can be a point next to the specified color, while spending 2 ¥.

Ideas: Title state very clearly that the current coordinates x, y, the current cost of cost, currently use magic can. After the board is normal to go, but it needs pruning or will TLE. The simplest idea is to prune

1. Memory search - recording current coordinates minimum cost, if multiple passes x, y and found that this cost is greater than the minimum cost i.e. return

2. optimality pruning - if the current cost> current optimal solution cut.

// luogu-judger-enable-o2

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

Int M
N, Int Tu = 19260817 ;
Int Ax [ 4 ] = { 0 , 0 , - L , L };
Int income [ 4 ] = { 1 , - 1 , 0 , 0 };
Int Yh [ L05 ] [ L05 ];
Int cost [ 105 ] [ 105 ] map [ 105 ] [ 105 ];
Bool Vis [ L05 ] [ L05 ];


void dfs(int x,int y,bool Can){
    if(cost < yh[x][y]) yh[x][y] = cost;
    else return;
    if(x == m && y == m){
        Min = cost;
        return;
    }
    for(int i = 0; i < 4; i++){
        int nx = x + ax[i];
        int ny = y + ay[i];
        if(vis[nx][ny] || nx > m || ny > m || nx < 1 || ny < 1) continue;
        if(Map[nx][ny] != 0){
            vis[nx][ny] = true;
            if(Map[x][y] == Map[nx][ny]) dfs(nx, ny, false);
            else{
                if(cost + 1 >= Min){
                    view [nx] [new] = false ;
                    Continue ;
                }
                cost++;
                dfs (nx, false );
                cost--;
            }
            view [nx] [new] = false ;
        }
        else{
            if(Can == true) continue;
            if(cost + 2 >= Min) continue;
            Map[nx][ny] = Map[x][y];
            cost += 2;
            vis [nx] [] = true ;
            
            dfs(nx, ny, true);
            
            view [nx] [new] = false ;
            Map [nx] [] = 0 ;
            cost -= 2;
        }
    }
}

void Read(){
    scanf("%d%d",&m,&n);
    for(int i = 1; i <= n; ++i){
        scanf("%d%d%d",&x,&y,&c);
        Map[x][y] = c + 1;
    }    
    vis[1][1] = 1;
    Memset (Yh, 0ksh3fa3fa3fa , Siseofa (Yh));
}

int main () {
    Read();
    dfs(1, 1, 0);
    if(Min == 19260817) printf("-1\n");
    else printf("%d\n", Min);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/LYFer233/p/12627918.html
dfs