https://www.luogu.org/problem/show?pid=1092
这道搜索折腾我好久。。结果还是TLE一个点。。
从后往前搜索,从上往下搜索
很多剪枝不一一说了看代码吧
90分代码
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
int n;
int A[30], B[30], C[30];
int h[30];
bool vi[30];
int dfs(int nowc, int nows, int ys, int a)
{
if (a==n+1)
{
//查看下面的算式是否合法,这里很重要,填完了数不代表前面的成立
if (nowc!=1)
{
int u = nowc; int YS = ys;
while (u>0)
{
if ((h[A[u]]+h[B[u]]+YS)%n!=h[C[u]]) return 0;
YS = (h[A[u]]+h[B[u]]+YS)/n;
u--;
}
}
for (int i=0;i<n;i++) printf("%d ", h[i]);
exit(0);
}
{
switch (nows)
{
case 1 :
{
if (h[A[nowc]]<0)
{
for (int i=0;i<n;i++)
{
if (!vi[i])
{
if (h[C[nowc]]>=0&&h[B[nowc]]>=0)
if ((i+h[B[nowc]]+ys)%n!=h[C[nowc]]) continue;
h[A[nowc]] = i;
vi[i] = true;
dfs(nowc, nows+1, ys, a+1);//DFSSSSSS
h[A[nowc]] = -1;
vi[i] = false;
}
}
} else dfs(nowc, nows+1, ys, a);//DFSSSSSS
break;
}
case 2 :
{
if (h[B[nowc]]<0)
{
for (register int i=0;i<n;i++)
{
if (!vi[i])
{
if (h[C[nowc]]>=0&&h[A[nowc]]>=0)
if ((i+h[A[nowc]]+ys)%n!=h[C[nowc]]) continue;
h[B[nowc]] = i;
vi[i] = true;
dfs(nowc, nows+1, ys, a+1);//DFSSSSSS
h[B[nowc]] = -1;
vi[i] = false;
}
}
}else dfs(nowc, nows+1, ys, a);//DFSSSSSS
break;
}
case 3 :
{
if (h[C[nowc]]<0)
{
if (h[A[nowc]]<0||h[B[nowc]]<0) return 0;
if (!vi[(h[A[nowc]]+h[B[nowc]]+ys)%n])
{
vi[(h[A[nowc]]+h[B[nowc]]+ys)%n] = true;
h[C[nowc]] = (h[A[nowc]]+h[B[nowc]]+ys)%n;
dfs(nowc-1, 1, (h[A[nowc]]+h[B[nowc]]+ys)/n, a+1);//DFSSSSSS
h[C[nowc]] = -1;
vi[(h[A[nowc]]+h[B[nowc]]+ys)%n] = false;
} else return 0;
} else
{
if ((h[A[nowc]]+h[B[nowc]]+ys)%n!=h[C[nowc]]) return 0;
dfs(nowc-1, 1, (h[A[nowc]]+h[B[nowc]]+ys)/n, a);//DFSSSSSS
}
break;
}
}
}
}
int main()
{
scanf("%d\n", &n);
for (int i=1;i<=n;i++) {char ch = getchar(); A[i] = ch-'A';}
scanf("\n");
for (int i=1;i<=n;i++) {char ch = getchar(); B[i] = ch-'A';}
scanf("\n");
for (int i=1;i<=n;i++) {char ch = getchar(); C[i] = ch-'A';}
ms(h, -1); ms(vi, false);
dfs(n,1,0,1);
return 0;
}