算法作业-密码问题(回溯法)

算法作业-密码问题(回溯法)_第1张图片
本题题意比较简单,就是从给出的字符串中选出5个,使其代入所给公式的值等于n。感觉过程基本就是穷举。

#include
#include
#include

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;

bool InResult(char c, vector<char>result)
{
     
	for (auto i : result)
		if (c == i)return true;
	return false;
}

bool cmp(vector<char>r1, vector<char>r2)
{
     
	for (auto i=0; i<5; i++){
     
		if (r1[i] > r2[i])
			return true;
	}
	return false;
}

void bestCode(int i, int sequence, const int &length, const string &str, int localN, int n,vector<char>result, vector<char>&bestResult, bool &flag)
{
     
	//i表示选取的第几个字母 0<=i<5 sequence 表示在str中序号
	if (i > 4) return;
	else
	{
     
		if (InResult(str[sequence], result))return;
		result.push_back(str[sequence]);
		if (i % 2 == 0)
			localN += (int)pow((str[sequence] - 'A') + 1, i + 1);
		else
			localN -= (int)pow((str[sequence] - 'A') + 1, i + 1);
		if (i == 4)
		{
     
			if (localN == n)
			{
     
				if (flag == false)
				{
     
					//第一个结果
					bestResult = result;
					flag = true;
				}
				else
				{
     
					if (cmp(result, bestResult))
						bestResult = result;
				}
			}
			return;
		}
		else
		{
     
			for (auto t = 0; t < length; t++)
				bestCode(i + 1, t, length, str, localN, n, result, bestResult, flag);
		}
	}
}

int main()
{
     
	int n;
	string str;
	while(cin>>n and n != 0)
	{
     
		cin >> str;
		const int length = str.length();
		vector<char>result;//记录可能的结果
		vector<char>bestResult;
		bool flag = false;//判断是否有结果
		for (auto i = 0; i < length; i++)
		{
     
			bestCode(0, i, length, str, 0, n, result, bestResult, flag);
		}
		if (flag == true)
			for (auto i = 0; i < bestResult.size(); i++)
				cout << bestResult[i];
		else cout << "no solution";
		cout << endl;
	}
}
/*
1 ABCDEFGHIGKL
11700519 ZAYEXIWOVU
3072997 SOUGHT
1234567 THEQUICKFROG
*/```

你可能感兴趣的:(算法作业,leetcode,算法,c++,字符串)