连连看 HDU

hdu有毒,考试上 AC 的就是一直 WA…
其实这道题是可以进行初始化来进行优化的,这样的话询问次数是可以达到 10510^5 的。不过普通的 dfsdfs + 剪枝也是可过的。
Code:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1000 + 2;
int G[maxn][maxn], n, m, q, a, b, c, d;
bool vis[maxn][maxn];
bool dfs(int dir, int times, int x, int y)
{
    if(x == c && y == d) return true;
    if(vis[x][y] || (G[y][x] && (x != a || y != b))) return false;      vis[x][y] = 1; 
    if(times > 3) return false;
    if(y <= 0 || x <= 0 || y > n || x > m) return false;
    if(times == 3)
    {
        if((dir == 1 || dir == 2) && y != d) return false;             
        if((dir == 3 || dir == 4) && x != c) return false;
        if(dir == 1 && x < c) return false;
        if(dir == 2 && x > c) return false;
        if(dir == 3 && y < d) return false;
        if(dir == 4 && y > d) return false;

        if(dir == 1){ if(dfs(dir, times, x - 1, y)) return true; }   
        if(dir == 2){ if(dfs(dir, times, x + 1, y)) return true; }
        if(dir == 3){ if(dfs(dir, times, x, y - 1)) return true; }
        if(dir == 4){ if(dfs(dir, times, x, y + 1)) return true; }
        return false;         
    }
    if(dir != 1) { if(dfs(1, times + 1, x - 1, y)) return true; }
    else if(dfs(1, times, x - 1, y)) return true;

    if(dir != 2) { if(dfs(2, times + 1, x + 1, y)) return true; }
    else if(dfs(2, times, x + 1, y)) return true;

    if(dir != 3) { if(dfs(3, times + 1, x, y - 1)) return true; }
    else if(dfs(3, times, x, y - 1)) return true;

    if(dir != 4) { if(dfs(4, times + 1, x, y + 1)) return true; }
    else if(dfs(4, times, x, y + 1)) return true;

    return false;
}
int main()
{
    while(scanf("%d%d",&n,&m) != EOF)
    {
        if(n == 0 && m == 0) break;
        for(int i = 1;i <= n; ++i)
            for(int j = 1;j <= m; ++j) scanf("%d",&G[i][j]);
        scanf("%d",&q);
        while(q--)
        {
            memset(vis, 0, sizeof(vis));
            int flag = 0;
            scanf("%d%d%d%d",&b,&a,&d,&c);
            if(G[b][a] != G[d][c] || G[b][a] == 0 || G[d][c] == 0) flag = 1;
            else
            {
                if(!dfs(0, 0, a, b)) flag = 1;
            } 
            if(flag) printf("NO
");
            else printf("YES
"); 
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/guangheli/p/9845109.html