P1092 虫食算 题解 DFS 深度优先搜索

这道题一开始自己写的时候,只有30分= =
然后参(模)考(仿)了洛谷第一个题解才写出来了(不过是在理解了的前提下,自己敲了一遍),下面附上参考的题解博客地址

参考的题解博客

我的代码:

#include<bits/stdc++.h>
using namespace std;
int n, cnt;
char s1[50], s2[50], s3[50];
int a[50], b[50], c[50];
int next[50];   //next数组用来记录下字母的出现顺序 
int num[50];	//num数组用来记录每个字母被赋的值, -1表示没被赋值 
int use[50]; 

int cut(){
	if(num[a[0]]+num[b[0]]>=n)
		return 1;
	
	int aa, bb, cc;
	for(int i=n-1; i>=0; i--){
		aa = num[a[i]], bb = num[b[i]], cc = num[c[i]];
		
		if(aa == -1 || bb == -1 || cc == -1)
			continue;
		
		if((aa+bb)%n!=cc&&(aa+bb+1)%n!=cc)
			return 1; 
	}
	
	return 0;
}

int check(){
	int aa, bb, cc, flag = 0;
	for(int i=n-1; i>=0; i--){
		aa = num[a[i]], bb = num[b[i]], cc = num[c[i]];
		
		if((aa+bb+flag)%n!=cc)
			return 0;
		
		flag = (aa+bb+flag)/n;
	}
	return 1;
}

void dfs(int x){
	if(cut())
		return;
	
	if(x==n){
		if(check()){
			for(int i=0; i<n; i++){
				printf("%d ", num[i]);
			}
			exit(0); //一定要加这句, 我没加这句2次都只有80分 
		}
	}
	
	for(int i=n-1; i>=0; i--){
		if(!use[i]){
			use[i] = 1;
			num[next[x]] = i;
			dfs(x+1);
			num[next[x]] = -1;
			use[i] = 0;
		}
	}
}

void getNext(int x){
	if(!use[x]){
		use[x] = 1;
		next[cnt++] = x;
	}
}

int main(){
	scanf("%d", &n);
	scanf("%s %s %s", s1, s2, s3);
	
	for(int i=0; i<n; i++){
		a[i] = s1[i] - 'A';
		b[i] = s2[i] - 'A';
		c[i] = s3[i] - 'A';
		num[i] = -1;
		use[i] = 0;
	}
	
	for(int i=n-1; i>=0; i--){
		getNext(a[i]);
		getNext(b[i]);
		getNext(c[i]);
	}
	
	memset(use, 0, sizeof(use));
	
	dfs(0);
	
	return 0;
}
发布了46 篇原创文章 · 获赞 1 · 访问量 2421

猜你喜欢

转载自blog.csdn.net/weixin_43708069/article/details/104002587