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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值