ACM刷题之hdu————Covering

Covering

Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1446    Accepted Submission(s): 589


Problem Description
Bob's school has a big playground, boys and girls always play games here after school.

To protect boys and girls from getting hurt when playing happily on the playground, rich boy Bob decided to cover the playground using his carpets.

Meanwhile, Bob is a mean boy, so he acquired that his carpets can not overlap one cell twice or more.

He has infinite carpets with sizes of  1×2 and  2×1, and the size of the playground is  4×n.

Can you tell Bob the total number of schemes where the carpets can cover the playground completely without overlapping?
 

Input
There are no more than 5000 test cases. 

Each test case only contains one positive integer n in a line.

1n1018
 

Output
For each test cases, output the answer mod 1000000007 in a line.
 

Sample Input
 
   
1 2
 

Sample Output
 
   
1 5
 

Source
2017ACM/ICPC广西邀请赛-重现赛(感谢广西大学)



用1 * 2 和 2 * 1 的方填满4 * n的格子。有几种填法。

这里猜测它应该有一个递推公式。

我们暴力出前10个答案,然后用高斯消元求出他的递推公式(具体怎么暴力的,就不细说了)

高斯消元其实就是解出多项式的系数方程。(用矩阵表示方程)

下面是高斯消元的代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn=105;
typedef double Matrix[maxn][maxn];
Matrix A,S;
//n是方程的个数
void gauss(Matrix A,int n)
{
    int i,j,k,r;
    for(int i=0; ifabs(A[r][i]))r=j;
        if(r!=i)
            for(j=0; j<=n; j++)swap(A[r][j],A[i][j]);
        for(k=i+1; k=0; i--)
    {
        for(j=i+1; j

我们运行后发现,系数是 1 5 1 -1

也就是 Fn = Fn-1 + 5Fn-2 + Fn-3 - Fn-4

这里我们就可以利用快速矩阵幂来计算了。

下面是ac代码

#include
using namespace std;
#define MID(x,y) ((x+y)>>1)
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int N=2e5+7;
typedef long long ll;
const long long mod=1e9+7;
typedef vector vec;
typedef vector mat;


mat mul(mat &A, mat &B) {
	mat C(A.size(), vec(B[0].size()));
	for (int i = 0 ; i < A.size(); i++) {
		for (int k = 0; k < B.size(); k++) {
			for (int j = 0; j < B[0].size(); j++) {
				// 注意负数要加mod  
				C[i][j] = (((C[i][j] + A[i][k] * B[k][j]) % mod) + mod ) % mod;
			}
		}
	}
	return C;
} 

mat pow(mat A, ll n) {
	mat B(A.size(), vec(A.size()));
	for (int i = 0; i < A.size(); i++) {
		B[i][i] = 1;
	}
	while (n > 0) {
		if (n & 1) B = mul(B, A);
		A = mul(A, A);
		n >>= 1;
	}
	return B;
}

ll n;

void solve() {
	mat A(4, vec(4));
	A[0][0]=1;  
    A[0][1]=5;
    A[0][2]=1;  
    A[0][3]=-1;
    
    A[1][0]=1;
    A[2][1]=1;
    A[3][2]=1;
    A = pow(A, n - 4);
    
    ll res = ((A[0][0] * 36) % mod + (A[0][1] * 11) % mod + (A[0][2] * 5) % mod + (A[0][3] * 1) % mod) % mod;
    
    printf("%LLd\n", res);
	
}


int main()
{
	while(cin>>n) {
		if (n == 1) {
			cout<<1<

你可能感兴趣的:(ACM题目,规律题,数学题,快速矩阵幂)