[Ybtoj High-Efficiency Advanced 1.4] [Deep Search] Worm Eater

[Ybtoj High-Efficiency Advanced 1.4] [Deep Search] Worm Eater

topic

Insert picture description here
Insert picture description here


Problem-solving ideas

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 number on the right is not filled,
    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


Code

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
string s[5];
char q[30];
int n,t,p[30],ans[30],use[30];
bool check()
{
    
    
     int w=0;
	 for (int i=n;i>0;i--)
	 {
    
    
	 	 
	 	 int x=ans[s[1][i-1]-64],y=ans[s[2][i-1]-64],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;
}
bool dfs(int x)
{     
	 if (x>n) return true;
	 for (int i=0;i<n;i++)
	     if (!use[i])
	     { 
	     	ans[q[x]-64]=i;
	     	use[i]=1; 
	     	if (check()&&dfs(x+1))
	     	   return true;
	     	use[i]=0; 
	     	ans[q[x]-64]=-1;
		 } 
	 return false;
}
int main()
{
    
    
	memset(ans,-1,sizeof(ans));
	scanf("%d",&n);
    cin>>s[1];
    cin>>s[2];
    cin>>s[3];
	for (int i=n;i>0;i--)
	    for (int j=1;j<=3;j++)
	        if (!p[s[j][i-1]-65])
	        {
    
    
	        	p[s[j][i-1]-65]=1;
	        	q[++t]=s[j][i-1]; 
			}
	dfs(1);
	for (int i=1;i<=n;i++)
	    printf("%d ",ans[i]);
	return 0; 
}

Guess you like

Origin blog.csdn.net/qq_45621109/article/details/112131816