ZOJ-1403-Safecracker(简单枚举)
https://zoj.pintia.cn/problem-sets/91827364500/problems/91827364902
题意:
密码序列由一系列大写字母组成,在解密序列不唯一的情况下,按字典序输出最后一个。
解密公式;
v-w^2+x^3-y^4+z^5=target
其中target是数字,由题目给出,v,w,x,y,z,属于同一个集合且各不相同,该集合由题目给出,由26个大写字母中任意5~12个组成,每个字母对应的数值,依次类推(A=1,B=2...).
思路:
这是一个枚举题型,题目中解的值域已定,只需要枚举5个变量的值,由于五个变量的范围不超过12,所以指数级别的枚举完全没问题。
由于按字典序的最后一个输出,就是字典序最大,所以事先排个序即可。
代码:
#include <iostream> #include <cmath> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; char letters[15]; int value[15], target; void solve(int len) { int a, b, c, d, e; for(a=0; a<len; a++) for(b=0; b<len; b++) if(a!=b) for(c=0; c<len; c++) if(b!=c&&a!=c) for(d=0; d<len; d++) if(a!=d&&b!=d&&c!=d) for(e=0; e<len; e++) if (a != e && b != e && c != e && d != e) { if (value[a] - pow(value[b], 2.0) + pow(value[c], 3.0) - pow(value[d], 4.0) + pow(value[e], 5.0) == target) { printf("%c%c%c%c%c\n", value[a] + 'A' - 1, value[b] + 'A' - 1, value[c] + 'A' - 1, value[d] + 'A' - 1, value[e] + 'A' - 1); return; } } printf("no solution\n"); } bool cmp(int a, int b) { return a > b; } int main() { while (cin >> target>>letters) { memset(value, 0, sizeof(value)); if (target == 0 && strcmp(letters, "END") == 0) return 0; int i = 0; while (letters[i]) { value[i] = letters[i] - 'A' + 1; i++; } sort(value, value + i, cmp); solve(i); } return 0; }