CodeForces 151D Quantity of Strings(并查集)

题目链接

D. Quantity of Strings
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109 + 7). Be careful and don't miss a string or two!

Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.

Input

The first and only line contains three integers: n, m and k (1 ≤ n, m, k ≤ 2000).

Output

Print a single integer — the number of strings of the described type modulo 1000000007 (109 + 7).

Sample test(s)
Input
1 1 1
Output
1
Input
5 2 4
Output
2
Note

In the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a").

In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb".

题意:用m种字符,构成长度为n的串,使得所有长度为K的串都为回文串。有多少种方案?

题解:如果第i个字符等于第j个字符,则将这两个字符加入同一个集合。对于不同的集合之间是没有相互影响的,求出独立的集合的个数即可求出答案。

代码如下:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<string.h>
#include<string>
#include<stdlib.h>
typedef __int64 LL;
typedef unsigned __int64 LLU;
const int nn=2100;
const int inf=0x3fffffff;
const int mod=1000000007;
const LL inf64=(LL)inf*inf;
using namespace std;
LL n,m,k;
int fa[nn];
int findfa(int x)
{
    if(fa[x]==x)
        return x;
    return fa[x]=findfa(fa[x]);
}
bool Union(int x,int y)
{
    int fx=findfa(x);
    int fy=findfa(y);
    if(fx!=fy)
    {
        fa[fx]=fy;
        return true;
    }
    return false;
}
LL po(LL x,int y)
{
    LL re=1;
    while(y)
    {
        if(y%2)
        {
            re=(re*x)%mod;
        }
        x=(x*x)%mod;
        y/=2;
    }
    return re;
}
int main()
{
    int i,j;
    while(scanf("%I64d%I64d%I64d",&n,&m,&k)!=EOF)
    {
        for(i=1;i<=n;i++)
            fa[i]=i;
        int ix=n;
        for(i=1;i<=n-k+1;i++)
        {
            for(j=1;j<=k/2;j++)
            {
                if(Union(i+j-1,i+k-j))
                    ix--;
            }
        }
        printf("%I64d\n",po(m,ix));
    }
    return 0;
}


你可能感兴趣的:(ACM,并查集,codeforces)