MG loves string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 131 Accepted Submission(s):
50
such a problem:
For a length of N , a random string made of lowercase letters, every time when it transforms, all
the character i will turn into a[i] .
MG states that the a[i] consists of a permutation .
Now MG wants to know the expected steps the
random string transforms to its own.
It's obvious that the expected steps
X will be a decimal number.
You should output X∗26Nmod 1000000007 .
And as for each case, there are 1 integer in the first line which indicate the length of random string(1<=N<=1000000000 ).
Then there are 26 lowercase letters a[i] in the next line.
line.
It's obvious that the expected steps X will be a decimal number.
You should output X∗26Nmod 1000000007 .
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
const int N_MAX = + ,INF= ;
int N;
string s;
vector<pair<int,int> >loop;//圈的大小<->圈的个数 ll gcd(ll a,ll b) {
if (b == )return a;
return gcd(b, a%b);
} ll lcm(ll a,ll b) {
return a / gcd(a, b)*b;
} void cal_loop() {
loop.clear();
int change[],vis[];
memset(vis,,sizeof(vis));
for (int i = ; i < s.size();i++) {
change[i] = s[i] - 'a';
}
map<int, int>m;
for (int i = ; i < ;i++) { if (vis[i])continue;
vis[i] = true;
int num = ;
int k = change[i];//k代表不断变化的字母
while (i != k) {
vis[k] = true;
num++;//该圈的元素个数加1
k = change[k];//!!!!!顺序
}
m[num]++;
}
for (map<int, int>::iterator it = m.begin(); it != m.end();it++) {
loop.push_back(*it);
}
} ll mod_pow(ll x,ll n) {//快速幂运算
ll res = ;
while (n>) {
if (n & )res = res*x%INF;
x = x*x%INF;
n >>= ;
}
return res;
} ll R_C(vector<int>&loop,int N) {//容斥原理,求由这些圈中的元素组成的长度为N的字符串的数量
ll permute = << (loop.size());
ll ans = ;
for (int i = ; i < permute;i++) {
int num = ;
int sum = ;
int sign=-;
for (int j = ; j < loop.size(); j++) {
if (i&( << j)) {
num++;//num记录利用到的圈的个数
sum += loop[j];//利用到的字符的总个数
}
}
if (num % == loop.size() % )//!!!!!!!!
sign = ;
ans =(ans+((sign*mod_pow(sum, N))%INF+INF)%INF)%INF;
}
return ans;
} ll solve(int N) {
cal_loop();
vector<int>vec;
ll ans = ;
for (int i = ; i < (<<loop.size());i++) {
ll change_time=;
vec.clear();
for (int j = ; j < loop.size();j++) {
if (i&( << j)) {
vec.push_back(loop[j].first*loop[j].second);
change_time = lcm(change_time, loop[j].first);
}
}
if (vec.size() > N)continue;//挑选出来的圈的个数不能超过字符串长度
ll number = R_C(vec, N);
ans = (ans + change_time*number) % INF;
}
return ans;
} int main() {
int T;
scanf("%d",&T);
while (T--) {
scanf("%d",&N);
cin >> s;
printf("%lld\n",solve(N));
}
return ;
}