题目链接:https://ac.nowcoder.com/acm/contest/890/E
思路:递归
首先给一个方块里的四个小方块编号:
01
23
其次数据结构采用链表,每个节点存一个(x,y)
对于一个2k*2k大方块,我们将链表分为四个小链表,每个链表里的数据分属自己的小块。如果我们知道他四个小方块的优先级,比如对于初始的大方块,优先级显然是0->2->3->1,如果solve(k,head)表示答案,那么solve里按顺序执行solve(k-1,h[0])->solve(k-1,h[2])->solve(k-1,h[3])->solve(k-1,h[1])
所以有以下伪代码:
solve(k,head)
if(k==0)输出head,return;
拆分head为四个小链表
solve(k-1,优先最高小链表)
solve(k-1,优先其次小链表)
solve(k-1,优先第三小链表)
solve(k-1,优先最低小链表)
显然这个算法是正确的,出口和拆分链表都简单,判断优先级是一个问题。
观察分形图,每个图都可以抽象为2*2的图,类似“凹”字,有一个开口,用0表示开口朝左,1表示上,2表示右,3表示下。观察知,对于每一个开口的图形,都有唯一的一个优先级序列与之对应,我们用dir数组存起来,dir[flag][i]表示当前图形(开口为flag)的优先级第i的块的编号。用dirflag[flag][i]表示当前图形(开口为flag)的优先级第i的块的开口。这样,已知图形开口为flag,我们就知道四个小块的优先级为dir[flag][0]->dir[flag][1]->dir[flag][2]->dir[flag][3],开口为dirflag[flag][0]->dirflag[flag][1]->dirflag[flag][2]->dirflag[flag][3]。如此就解决了优先级的问题。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
struct Node
{
int x,y;
Node *next;
};
int dir[4][4]=
{
0,1,3,2,
0,2,3,1,
3,2,0,1,
3,1,0,2
};
int dirflag[4][4]=
{
1,0,0,3,
0,1,1,2,
3,2,2,1,
2,3,3,0
};
void solve(int k,int dx,int dy,Node *head,int flag)
{
if(!k)//出口
{
printf("%d %d\n",head->x,head->y);
return ;
}
Node *h[4],*t[4],*p=head;
for(int i=0; i<4; i++)h[i]=t[i]=NULL;
int st=(1<<(k-1));
while(p)//拆分链表
{
if(p->x-dx<=st)
{
if(p->y-dy<=st)
{
if(h[0]==NULL)h[0]=t[0]=p;
else
{
t[0]->next=p;
t[0]=t[0]->next;
}
}
else
{
if(h[1]==NULL)h[1]=t[1]=p;
else
{
t[1]->next=p;
t[1]=t[1]->next;
}
}
}
else
{
if(p->y-dy<=st)
{
if(h[2]==NULL)h[2]=t[2]=p;
else
{
t[2]->next=p;
t[2]=t[2]->next;
}
}
else
{
if(h[3]==NULL)h[3]=t[3]=p;
else
{
t[3]->next=p;
t[3]=t[3]->next;
}
}
}
Node *q=p;
p=p->next;
q->next=NULL;
}
for(int i=0; i<4; i++)
{
if(h[dir[flag][i]]==NULL)continue;
int df=dirflag[flag][i];
solve(k-1,dx+(h[dir[flag][i]]->x>dx+st?st:0),dy+(h[dir[flag][i]]->y>dy+st?st:0),h[dir[flag][i]],df);
}
}
int main()
{
int n,k;
scanf("%d%d",&n,&k);
Node *head=new Node;
Node *tail=head;
scanf("%d%d",&tail->x,&tail->y);
for(int i=2; i<=n; i++)
{
tail->next=new Node;
tail=tail->next;
scanf("%d%d",&tail->x,&tail->y);
}
tail->next=NULL;
solve(k,0,0,head,1);
return 0;
}
/*
2 3
1 1
1 2
*/