P1911的题解

· · 题解

P1911——一道简单的分治题

举个例子

在 n=2,x=1,y=1 时:

0 1
1 1

然而 在 n=3,x=1,y=1 时:

0 1 2 2
1 1 3 2
4 3 3 5
4 4 5 5

在 n=4,x=1,y=1 时:

0 1 2 2 7 7 10 10
1 1 3 2 7 8 8 10
4 3 3 5 6 6 8 9
4 4 5 5 16 6 9 9
14 14 11 16 16 17 18 18
14 13 11 11 17 17 19 18
15 13 13 12 20 19 19 21
15 15 12 12 20 20 21 21

仔细观察一下

一个长度为 2^n 的表格

如图:

0 1 2 2 4 4 5 5
1 1 3 2 4 3 3 5
4 3 3 5 1 1 3 2
4 4 5 5 0 1 2 2
2 2 1 0 0 1 4 4
2 3 1 1 1 1 3 4
5 3 3 4 2 3 3 5
5 5 4 4 2 2 5 5

(中间的 0 组成一个 L 型军营)

是四个长度为 2^{n-1} 的表格组成的

上代码

#include<bits/stdc++.h>
using namespace std;
int n,xx,yy,table[2000][2000],cnt,q[4000000],tot,dx[4]={0,1,0,1},dy[4]={0,0,1,1},x_[4]={1,0,1,0},y_[4]={1,1,0,0};
void f_(int x,int y,int c,int a,int b)
{
    if(!c)
    {
        return;
    }
    c--;
    cnt++;
    int t=cnt;
    for(int i=0;i<4;i++)
    {
        int sx=x+(dx[i]<<c),sy=y+(dy[i]<<c),f=sx+(x_[i]<<c)-x_[i],g=sy+(y_[i]<<c)-y_[i];
        if(a>=sx&&a<sx+(1<<c)&&b>=sy&&b<sy+(1<<c))
        {
            f_(sx,sy,c,a,b);
        }
        else
        {
            f_(sx,sy,c,f,g);
            table[f][g]=t;
        }
    }
}
int main()
{
    cin>>n>>xx>>yy;
    f_(1,1,n,xx,yy);
    for(int i=1;i<=1<<n;i++)
    {
        for(int l=1;l<=1<<n;l++)
        {
            if(i!=xx||l!=yy)
            {
                if(!q[table[i][l]])
                {
                    tot++;
                    q[table[i][l]]=tot;
                }
                cout<<q[table[i][l]]<<" ";
            }
            else
            {
                cout<<"0 ";
            }
            if(l==(1<<n))
            {
                cout<<"\n";
            }
        } 
    }
}