zoukankan      html  css  js  c++  java
  • 专题三--1009

    这一道题是看题解过的,实在是太难了。。好难找的规律。。好坑的思路。在我的这个博客里引用http://m.blog.csdn.net/article/details?id=50638393 中的题解思路,这个题解还使用了矩阵快速幂的方法,具体见这个blog

    题目

    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 2L 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
    

    思路

    用f(n)表示n个人满足条件的结果,那么如果最后一个人是m的话,那么前n-1个满足条件即可,就是f(n-1);
    如果最后一个是f那么这个还无法推出结果,那么往前再考虑一位:那么后三位可能是:mmf, fmf, mff, fff,其中fff和fmf不满足题意所以我们不考虑,但是如果是
    mmf的话那么前n-3可以找满足条件的即:f(n-3);如果是mff的话,再往前考虑一位的话只有mmff满足条件即:f(n-4)
    所以f(n)=f(n-1)+f(n-3)+f(n-4),递推会跪,可用矩阵快速幂
    构造一个矩阵:
    pic

    代码

    1. #include<iostream>
    2. #include<stdio.h>
    3. usingnamespace std;
    4. int n,m;
    5. int f[5]={0,2,4,6,9};
    6. int a[4][4],b[4][4],c[4][4];
    7. void multi(int(*x)[4],int(*y)[4])
    8. {
    9. int i,j,k;
    10. for(i=0;i<4;i++)
    11. for(j=0;j<4;j++)
    12. for(c[i][j]=k=0;k<4;k++)
    13. c[i][j]+=x[i][k]*y[k][j];
    14. for(i=0;i<4;i++)
    15. for(j=0;j<4;j++)
    16. x[i][j]=c[i][j]%m;
    17. }
    18. int main()
    19. {
    20. //freopen("date.in","r",stdin);
    21. //freopen("date.out","w",stdout);
    22. int i,j;
    23. while(scanf("%d%d",&n,&m)==2)
    24. {
    25. if(n<=4){printf("%d ",f[n]%m);continue;}
    26. a[0][0]=a[0][2]=a[0][3]=1,a[0][1]=0;
    27. a[1][0]=1,a[1][1]=a[1][2]=a[1][3]=0;
    28. a[2][0]=a[2][2]=a[2][3]=0,a[2][1]=1;
    29. a[3][0]=a[3][1]=a[3][3]=0,a[3][2]=1;
    30. for(i=0;i<4;i++)
    31. for(j=0;j<4;j++)
    32. b[i][j]=(i==j);
    33. for(n-=4;n;multi(a,a),n>>=1)if(n&1)multi(b,a);
    34. for(j=0,i=0;i<4;i++)j+=b[0][i]*f[4-i];
    35. printf("%d ",j%m);
    36. }
    37. return0;
    38. }





  • 相关阅读:
    form和button和input
    onmouseover和onfocus和select一起完成的操作
    事件和事件句柄的理解
    onunload对应的js代码为什么不能执行?和onbeforeunload的区别?
    表单及其控件的了解
    表单及其控件的访问
    【JAVA SE基础篇】59.同步块、并发容器和死锁
    【JAVA SE基础篇】58.线程并发的非同步、同步与锁机制
    【JAVA SE基础篇】57.线程礼让、插队、优先调用、守护线程与其他
    【JAVA SE基础篇】56.线程状态、方法
  • 原文地址:https://www.cnblogs.com/liuzhanshan/p/5538738.html
Copyright © 2011-2022 走看看