Worm Eater
Topic link: Worm Food Calculation
Thanks @ lzh @lzh@ l z h Big guy's help
Title description
Problem solving ideas
Obviously this is a deep search question (otherwise how could it be included in the deep search column) .
You can search through each letter to find the best answer.
But this is O (1 0 n) O(10^n)O ( 1 0The time complexity of n )is definitely not enough, so pruning must be added.
If the current situation is no longer legal, it will naturally not be possible to search.
So now the key is check () check ()c h e c k ( ) function.
If all three numbers in the current position have been searched, just judge it directly. But if the number of the previous one is unknown, then at most one can contribute 1 11 。
The last one must be judged specially: whether it is a carry or not, it is illegal.
code
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int n,tot,ok;
int v[30];
int b[20];
int ans[30];
char ss[30];
string s[4];
int check()
{
int t=0;
for(int i=n-1;i>=0;i--)
{
int a=ans[s[1][i]-'A'];
int b=ans[s[2][i]-'A'];
int c=ans[s[3][i]-'A'];
if(a!=-1&&b!=-1&&c!=-1)
{
if(t!=-1)
{
if((a+b+t)%n!=c)
return 0;
if(i==0&&a+b+t>=n)
return 0;
t=(a+b+t)/n;
}
else
{
if((a+b)%n!=c&&(a+b+1)%n!=c)
return 0;
if(i==0&&a+b>=n)
return 0;
}
}
else
t=-1;
}
return 1;
}
void dfs(int dep)
{
if(ok)
return;
if(dep>n)
{
ok=1;
for(int i=0;i<n;i++)
cout<<ans[i]<<" ";
return;
}
for(int i=0;i<n;i++)
{
if(!b[i])
{
b[i]=1;
ans[ss[dep]-'A']=i;
if(check())
dfs(dep+1);
b[i]=0;
ans[ss[dep]-'A']=-1;
}
}
}
int main()
{
cin>>n;
cin>>s[1]>>s[2]>>s[3];
for(int i=n-1;i>=0;i--)
for(int j=1;j<=3;j++)
if(!v[s[j][i]-'A'])
{
v[s[j][i]-'A']=1;
ss[++tot]=s[j][i];
}
memset(ans,-1,sizeof(ans));
dfs(1);
}