hdu2604——Queuing

本文深入探讨了HDOJ2604问题的背景、定义及其解决策略。重点阐述了如何通过数学归纳法和动态规划思想,将复杂的问题简化并求解。此外,提供了具体的代码实现,帮助读者理解和应用相关算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hdu2604——Queuing:http://acm.hdu.edu.cn/showproblem.php?pid=2604

Queuing

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3932    Accepted Submission(s): 1730


Problem Description
Queues and Priority Queues are data structures which are known to most computer scientists. The Queue occurs often in our daily life. There are many people lined up at the lunch time. 

  Now we define that ‘f’ is short for female and ‘m’ is short for male. If the queue’s length is L, then there are 2 L numbers of queues. For example, if L = 2, then they are ff, mm, fm, mf . If there exists a subqueue as fmf or fff, we call it O-queue else it is a E-queue.
Your task is to calculate the number of E-queues mod M with length L by writing a program.
 

Input
Input a length L (0 <= L <= 10  6) and M.
 

Output
Output K mod M(1 <= M <= 30) where K is the number of E-queues with length L.
 

Sample Input
  
3 8 4 7 4 8
 

Sample Output
  
6 2 1
题意:有每个队有L个人,共有2^L个对,f代表女性,m代表男性,若队中包含fff 或fmf则算O队,否则算E队。

引用大神分析:

1、考虑最后一位为m,则只需考虑前l-1个人满足条件就行,即f(l-1);

2、若最后一位为f,再往前推一位(mf或ff),还是无法确定,再往前推一位,有fff、fmf、mmf、mff,前两种不满足,只用考虑后两种情况。当为mmf时,只需考虑前l-3个人满足条件就行,即f(l-3);当为mff时,无法确定(若倒数第四位是f就不满足条件了),因此还得再往前推一位(前l-4个),此时只需考虑f(l-4);

因此f[l] = f[l - 1] + f[l - 3] + f[l - 4].递推式出来了那个初始矩阵也就出来了。

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <set>
#include <queue>

using namespace std;

int mod,n;
typedef long long LL;

int f[] = {1,2,4,6,9};
typedef struct Node
{
    LL a[4][4];
} node;

node fun(node x,node y)
{
    node ans = {0,0,0,0,
                0,0,0,0,
                0,0,0,0,
                0,0,0,0
               };
    for(int i = 0; i < 4; i++)
        for(int j = 0; j < 4; j++)
            for(int k = 0; k < 4; k++)
                ans.a[i][j] += (x.a[i][k] * y.a[k][j]) % mod,
                               ans.a[i][j] %= mod;
    return ans;
}
LL quickpow(long long x)
{
    node ans = {9,6,4,2,
                0,1,0,0,
                0,0,1,0,
                0,0,0,1
               };
    node p = {1,1,0,0,
              0,0,1,0,
              1,0,0,1,
              1,0,0,0
             };
    while(x)
    {
        if(x & 1)ans = fun(ans,p);
        x >>= 1;
        p = fun(p , p);
    }
    return ans.a[0][0] % mod;
}
int main()
{
//    freopen("in.txt","r",stdin);
    while(~scanf("%d%d",&n,&mod))
    {
        if(n <= 4)printf("%d\n",f[n] % mod);
        else printf("%lld\n",quickpow(n - 4));
    }
    return 0;
}


http://blog.youkuaiyun.com/hcbbt/article/details/38363353


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值