http://acm.hdu.edu.cn/showproblem.php?pid=5651
题意:生成回文串。输出所有回文串的可能数。
题解:mod除法会损失高位,用逆元来代替除法,模板如下
ac代码:
#include<stdio.h> #include<string.h> #include<iostream> #include<string> using namespace std; const int maxn = 1111; int num[maxn]; //char s[maxn]; typedef long long ll; const int mod = 1e9 + 7; ll f[maxn]; void init() { f[1] = 1; f[0] = 1; for (int i = 2; i < maxn; i++) f[i] = f[i - 1] * i%mod; } ll cal(ll x) { ll res = 1; int k = mod - 2; while (k) { if (k & 1) { res *= x; res %= mod; } x*=x; x %= mod; k >>= 1; } return res;//cal(x^ mod) } int main() { int t; init(); cin >> t; while (t--) { memset(num, 0, sizeof(num)); string s; cin >> s; int n = s.length(); for (int i = 0; i < n; i++) { num[s[i]]++; } int cnt = 0; for (int i = 'a'; i <= 'z'; i++) { if (num[i] & 1) cnt++; } if (cnt > 1) { cout << 0 << endl; continue; } int sum = 0; for (int i = 'a'; i <= 'z'; i++) { num[i] /= 2; sum += num[i]; } ll res = f[sum]; for (int i ='a'; i <='z'; i++)if(num[i]) { res = res*cal(f[num[i]]) % mod; } cout << res<<endl; } }