日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

(回文串全排列个数) xiaoxin juju needs help

發布時間:2025/3/12 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (回文串全排列个数) xiaoxin juju needs help 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

As we all known, xiaoxin is a brilliant coder. He knew palindromic strings when he was only a six grade student at elementry school.

This summer he was working at Tencent as an intern. One day his leader came to ask xiaoxin for help. His leader gave him a string and he wanted xiaoxin to generate palindromic strings for him. Once xiaoxin generates a different palindromic string, his leader will give him a watermelon candy. The problem is how many candies xiaoxin’s leader needs to buy?
Input
This problem has multi test cases. First line contains a single integer T(T≤20) which represents the number of test cases.
For each test case, there is a single line containing a string S(1≤length(S)≤1,000).
Output
For each test case, print an integer which is the number of watermelon candies xiaoxin’s leader needs to buy after mod 1,000,000,007.
Sample Input
3
aa
aabb
a
Sample Output
1
2
1

分析與解答

參考代碼以及思路:
https://www.cnblogs.com/shentr/p/5349489.html
https://blog.csdn.net/fun_zero/article/details/50989103
真的十分奇怪,這題我用小費馬求逆元,wrong answer。之前小費馬求出來的都不用判斷逆元的正負,我估計還是錯在逆元的正負上了,最后改也沒改出來,用歐幾里得求逆元倒是求出來了
1.回文串的性質
給你n個字母,求可以組成的回文串的個數
1.1。形成回文串的條件
1.n為奇數,有一個字母的個數為奇數
2.n為偶數,字母個數全為偶數
所以回文串中最多僅有一個字母個數為奇數
滿足這一條件才能夠形成回文串
1.2。回文串的所有組成的可能情況
設回文串的長度為n,則左邊的長度為n/2
由于回文串關于中點對稱,所以只要滿足形成回文串的條件,我們就只需找左邊的所有可能情況,如果左邊每個字母都是只出現一次,那么就是(n/2)!,但是這里可能有重復情況,那么就(n/2)!/(ni!nj! …),這里ni!中的ni是整個串中字符i出現的次數/2(因為是左邊),這個是高中有重復排列的公式
2.求模
由于有除法,所以先求逆元,轉換為乘法就ok了

#include<iostream> #include<cstdio> #include<cstring> using namespace std; typedef long long LL; const LL MOD=1e9+7; int cnt[260]; char ch[1005];LL jiecheng(int n)//求階乘 {if(n==0)return 1;LL ans=1;for(int i=1;i<=n;i++)ans=ans*i%MOD;return ans; }LL x,y; LL gcd(LL a,LL b)//歐幾里得 需要找a的逆元,b是mod,x是最終求出的一個逆元 {LL t,d;if(b==0){x=1,y=0;return a;}d=gcd(b,a%b);t=x, x=y, y=t-(a/b)*y;return d;}int main() {int t;cin>>t;while(t--){memset(cnt,0,sizeof(cnt));scanf("%s",ch);int len=strlen(ch);for(int i=0;i<len;i++){cnt[ch[i]-' ']++;}int count=0;for(int i=0;i<260;i++){if(cnt[i]&1)//如果是奇數就count++ count++;cnt[i]/=2;//只用左半部分 }if(count>1)//回文串中最多只能有一個字母的個數為奇數 {cout<<0<<endl;continue;}LL ans=jiecheng(len/2)%MOD;for(int i=0;i<260;i++){if(cnt[i]>0){gcd(jiecheng(cnt[i]),MOD);//依次求每個字符重復的個數得階乘 if(x<0)x+=MOD;ans=ans*x%MOD;}}cout<<ans<<endl;} }

總結

以上是生活随笔為你收集整理的(回文串全排列个数) xiaoxin juju needs help的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。