analysis
Record the order of appearance of the letters (from right to left) and
enumerate the possible numbers for each letter
a is addend one, b is addend two, c is sum
When these three numbers have been filled in
- If (a+b+w)%n!=c is not feasible,
it is not feasible if there is a carry in the highest bit - When the right side is still unfilled
if (a+b)%n!=c and (a+b+1)%n!=c, it is not feasible.
If the highest bit has a carry, it is not feasible,
otherwise the carry is assigned to -1
Upload code
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
string s[10];
char f[30];
int n,t,p[30],ans[30],u[30];
bool check()
{
int w=0;
for(int i=n;i>0;i--)
{
int x=ans[s[1][i-1]-64];
int y=ans[s[2][i-1]-64];
int z=ans[s[3][i-1]-64];
if(x!=-1&&y!=-1&&z!=-1)
{
if(w!=-1)
{
if((x+y+w)%n!=z) return false;
if(i==1&&x+y+w>=n) return false;
w=(x+y+w)/n;
}
else
{
if((x+y)%n!=z&&(x+y+1)%n!=z) return false;
if(i==1&&x+y>n) return false;
}
}
else w=-1;
}
return true;
}
int dfs(int x)
{
if(x>n) return 1;
for(int i=0;i<=n-1;i++)
{
if(!u[i])
{
ans[f[x]-64]=i;
u[i]=1;
if(check()&&dfs(x+1))
{
return 1;
}
u[i]=0;
ans[f[x]-64]=-1;//回溯
}
}
return 0;
}
int main()
{
memset(ans,-1,sizeof(ans));
cin>>n;
cin>>s[1];
cin>>s[2];
cin>>s[3];
for(int i=n;i>=1;i--)
{
for(int j=1;j<=3;j++)
{
if(!p[s[j][i-1]-65])
{
p[s[j][i-1]-65]=1;
f[++t]=s[j][i-1];
}
}
}
dfs(1);
for(int i=1;i<=n;i++)
{
cout<<ans[i]<<' ';
}
return 0;
}