[ARC064F] Rotated Palindromes

The meaning of problems

Given an integer N, you determine how much of the character set is an integer between 1 to K string so that the string can be N palindromic sequence obtained after cyclic shift by one length. The so-called cyclic shift, is to a prefix string (which may be empty) to the end of the string, such as "1221" cyclic shift can be "1221", "2211", "2112", "1122" four string. Results of $ 10 $ ^ 7 + 9 mod

answer

It took almost an hour exam pushed a $ O (n) $ formula, but also to optimize delusion to $ O (sqrt (n)) $ ......

First, consider a palindrome string contribution to the answer:

Provided that a minimum cycle length of section len.

Its contribution is len.

 

But a palindrome string loop section must also palindrome string (do not understand can look at this: abcabcabc)

So for len is an even number, the cycle can be detached from the intermediate section, which causes the same cycle before and after the swap section after section, e.g. 2112,1221 will expand as a result, so the contribution of this time is divided by 2 .

But if the length is an odd number, because of an intermediate, the longitudinal extension swap out subsequent stage still different results, it is not divided by two.

 

Because the same palindrome string len contribution to the same answer , so for each number palindrome string len, statistics can be represented.

And because len must be a factor of n (where else to loop) , so that direct root factor n n to the pre-treatment.

Code

#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
#define int long long
#define mod (int)1000000007
#define N 64000
vector<int> vec;
int tot[N];
int pow(int base,int up)
{
	int ans=1;
	while(up)
	{
		if(up&1) ans*=base,ans%=mod;
		base*=base;
		base%=mod;
		up>>=1;
	}
	return ans;
}
signed main()
{
	int n,k,len;
	cin>>n>>k;
	len=sqrt(n);
	for(int i=1;i<=len;i++) if(n%i==0)//获取所有可能的循环节长度
	{
		vec.push_back(i);
		IF (= n-I / I!) vec.push_back (n-/ I); 
	} 
	Sort (vec.begin (), vec.end ()); 
	int ANS = 0; 
	for (int I = 0; I <VEC. size (); I ++) 
	{ 
		TOT [I] = POW (K, (vec [i] + 1'd) / 2); // number of cycle length section vec [i] the loop section. Because palindromic sequence, it is only necessary to know the entire front half of the palindromic sequence can be determined, the following is the same reason 
		for (int j = 0; j <i; j ++) if (vec [i]% vec [j] = 0 =) 
		TOT [I] - TOT = [J], TOT [I] = (TOT [I] + MOD) MOD%; // [removed length vec [i]] section of the internal circulation loop containing sections where 
		IF (VEC [I] &. 1) ANS + = [I] * VEC [I] TOT, ANS% = MOD; 
		the else ANS + = TOT [I] * (VEC [I] / 2), ANS% = MOD; 
	} 
	COUT < <ANS; 
}

  

Guess you like

Origin www.cnblogs.com/linzhuohang/p/11519936.html