HDU-1015Safecracker(DFS)

题目:传送门
分析:题意大概是给出一串字母,每个字母有自己代表的数字,找出字母中5个符合公式 的字母,并且有相同时,要按字典来排序。
解题思路:DFS遍历所有情况,回溯时注意一下字符串比较
AC代码:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
map<char,int>mm;
char c1[10000],ch[10000],max_ch[10000];
int n1[100],len,target;
bool vis[100];
void fun() {				//打表,将字母转换为数字
	char c='A';
	for(int i=1; i<=26; i++)
		mm[c++]=i;
}
int is(int a,int b,int c,int d,int e,int t) {			//判断是否符合公式
	if(a-b*b+c*c*c-d*d*d*d+e*e*e*e*e==t)	return 1;
	else return 0;
}
void dfs(int num) {				
	if(num==5) {
		if(is(n1[0],n1[1],n1[2],n1[3],n1[4],target)&&strcmp(ch,max_ch)>0) {
			strcpy(max_ch,ch);
		}
	} else {
		for(int i=0; i<len; i++) {
			if(!vis[mm[c1[i]]]) {		//判断是否走过
				n1[num]=mm[c1[i]];
				ch[num]=c1[i];
				vis[mm[c1[i]]]=true;		//标记一下走过
				dfs(num+1);
				vis[mm[c1[i]]]=false;
			}
		}
	}
}
int main() {
	fun();
	while(cin>>target>>c1) {
		if(target==0&&!strcmp(c1,"END"))	break;
		memset(ch,'\0',sizeof(ch));
		memset(max_ch,'\0',sizeof(max_ch));
		memset(vis,false,sizeof(vis));
		memset(n1,0,sizeof(n1));
		len=strlen(c1);
		sort(c1,c1+len);
		dfs(0);
		if(strlen(max_ch)==0)	cout<<"no solution"<<endl;
		else cout<<max_ch<<endl;

	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43556295/article/details/86663254