poj 3420

http://poj.org/problem?id=3420
poj 2663升级版,注意不用的边可以删除以缩小矩阵规模,可以有自环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<iostream>
#define mem(x,y) memset(x,y,sizeof(x))
#define inf 0x3f3f3f3f
using namespace std;
#define siz 6
#define Mytype int
int N=6;
Mytype mod;
struct matrix
{
Mytype a[siz][siz];
matrix operator*(const matrix &y)const
{
matrix res;
mem(res.a,0);
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
if(a[i][j])
for(int k=0;k<N;k++)
res.a[i][k]+=a[i][j]*y.a[j][k],res.a[i][k]%=mod;
return res;
}
matrix operator+(const matrix &y)const
{
matrix res;
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
res.a[i][j]=a[i][j]+y.a[i][j],res.a[i][j]%=mod;
return res;
}
matrix operator*=(const matrix &y)
{
*this=y* *this;
return *this;
}
};
matrix qmod(matrix a,int k)
{

matrix res;
mem(res.a,0);
for(int i=0;i<N;i++)
res.a[i][i]=1;
while(k)
{
if(k&1)
res*=a;
a*=a;
k>>=1;
}
return res;
}
int ans[35];
int main()
{

matrix a;
mem(a.a,0);
a.a[4][1]=1;
a.a[5][1]=1;
a.a[3][2]=1;
a.a[5][2]=1;
a.a[2][3]=1;
a.a[1][4]=1;
a.a[5][4]=1;
a.a[0][5]=1;
a.a[1][5]=1;
a.a[2][5]=1;
a.a[4][5]=1;
a.a[5][0]=1;
a.a[5][5]=1;
int k;
while(scanf("%d%d",&k,&mod),k)
{
matrix ans=qmod(a,k+1);
int res=ans.a[5][0];
printf("%d\n",res);
}
}

EOF