NOIP会考矩乘?看了一下blog,在代码上改得比较易懂一点。。

这道2次二分作为矩乘的开始

 1 //#include<bits/stdc++.h>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<iostream>
 6 #include<queue>
 7 #define inc(i,l,r) for(i=l;i<=r;i++)
 8 #define dec(i,l,r) for(i=l;i>=r;i--)
 9 #define mem(a) memset(a,0,sizeof(a))
10 #define ll long long
11 #define succ(x) (1<<x)
12 #define NM 100
13 using namespace std;
14 int read(){
15     int x=0,f=1;char ch=getchar();
16     while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
17     while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
18     return x*f;
19 }
20 struct matrix{
21     int a[NM][NM];
22 }a,b;
23 int i,j,n,k,inf;
24 matrix operator+(const matrix&x,const matrix&y){
25     matrix s;
26     int i,j;
27     inc(i,1,n)
28     inc(j,1,n)
29     (s.a[i][j]=x.a[i][j]+y.a[i][j])%=inf;
30     return s;
31 }
32 matrix operator*(const matrix&x,const matrix&y){
33     matrix s;
34     int i,j,k;
35     inc(i,1,n)
36     inc(j,1,n){
37         s.a[i][j]=0;
38         inc(k,1,n)
39         (s.a[i][j]+=x.a[i][k]*y.a[k][j])%=inf;
40     }
41     return s;
42 }
43 matrix cal(int k){
44     matrix t=a,s=a;
45     k--;
46     while(k>0){
47         if(k%2)s=s*t;
48         t=t*t;
49         k/=2;
50     }
51     return s;
52 }
53 matrix sum(int x){
54     matrix tmp,s,t;
55     if(x==1)return a;
56     t=cal(x/2);
57     tmp=sum(x/2);
58     if(x%2){
59         s=t*tmp;
60         s=s+tmp;
61         s=s+cal(x);
62     }else{
63         s=t*tmp;
64         s=s+tmp;
65     }
66     return s;
67 }
68 int main(){
69     n=read();k=read();inf=read();
70     inc(i,1,n)
71     inc(j,1,n)a.a[i][j]=read();
72     b=sum(k);
73     inc(i,1,n){
74         inc(j,1,n)printf("%d ",b.a[i][j]);
75         printf("\n");
76     }
77     return 0;
78 }
View Code

 

posted on 2015-10-14 20:01  onlyRP  阅读(118)  评论(0编辑  收藏  举报