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.

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
引用大神分析:
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