题意:
- 输入 n n 和 字符串 ,代表 字符串 s s 的长度为
- 正着选 n n 个字符构成一个字符串 ,然后倒着选 n n 个字符构成一个字符串 ,不能选重复的字符。
问:字符串 s1 s 1 与 字符串 s2 s 2 完全一样的的方案数是多少?
数据范围:
- 1<=n<=18 1 <= n <= 18
- 字符串 s s 都是小写字母
输入:
4
cabaacba
18
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
输出:
4
9075135300
[The answer may not be representable as a 32-bit integer.]
样例解释:
- [c] a b a [a] c [b] [a]
- [c] a b [a] a c [b] [a]
- c [a] [b] [a] a [c] b a
- c [a] [b] a [a] [c] b a
解题思路:
因为字符串长度最大为36,那么我们可以先分成两半,然后二进制暴力枚举。0 代表倒着的,1 代表正着的。然后要相互对称。
AC代码:
#include<cstdio>
#include<algorithm>
#include<map>
#include<cstring>
#include<cmath>
#include<iostream>
using namespace std;
typedef long long LL;
map<pair <string,string>,LL> cnt;
const int maxn = 50;
char s[maxn];
int main(){
int n; scanf("%d",&n);
scanf("%s",s);
for(int i = 0;i < (1 << n);i++){ // 先枚举左半边
string s1 = "",s2 = "";
for(int j = 0;j < n;j++){
if(i & (1 << j)) s1 += s[j]; // 若 i 的第 j 位为 1,则 s[j] 加入 s1.
else s2 += s[j]; // 若 i 的第 j 位为 0,则 s[j] 加入 s2.
}
cnt[make_pair(s1,s2)]++; // 开个 map 来记录有(s1,s2)有多少对
}
LL sum = 0;
for(int i = 0;i < (1 << n);i++){ // 枚举右半边
string s1 = "",s2 = "";
for(int j = n - 1;j >= 0;j--){
if(i & (1 << j)) s2 += s[j + n]; // 若 i 的第 j 位为 1,则 s[j + n] 加入 s2.
else s1 += s[j + n]; // 若 i 的第 j 位为 0,则 s[j + n] 加入 s1.
}
sum += cnt[make_pair(s1,s2)]; // 因为 s1 和 s2 要相等所以要对称相等
}
printf("%lld\n",sum);
}