码迷,mamicode.com
首页 > 其他好文 > 详细

hust 1013 Grid

时间:2014-05-10 19:00:03      阅读:337      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

题目描述

There is a grid size of 1*N. The spanning tree of the grid connects all the vertices of the grid only with the edges of the grid, and every vertex has only one path to any other vertex. Your task is to find out how many different spanning trees in a given grid.

输入

Every line there is a single integer N(0 < N <= 1000000000), a line of 0 represents the end of the input.

输出

Every line you should only print the result, as the result may be very large, please module it with 1000000007.

样例输入

1
2
0

样例输出

4
15

提示When N=1, the spanning trees are an follows: _ |_ , |_| , _ _| , _ | | . There are four ways to construct the spanning tree.

简单的矩阵快速幂,不过在找前几项时要用到矩阵的行列式来求,求递推式就简单了f[n]=4*f[n-1]-f[n-2]

bubuko.com,布布扣
#include <iostream>
#include <cstdio>
using namespace std;
struct Mat
{
    long long matrix[2][2];
};
Mat Multi(const Mat& a, const Mat& b)
{
int i, j, k;
Mat c;
for (i = 0; i < 2; i++)
{
   for (j = 0; j < 2; j++)
   {
    c.matrix[i][j] = 0;
    for (k = 0;k < 2; k++)
     c.matrix[i][j] += a.matrix[i][k] * b.matrix[k][j] % 1000000007;
    c.matrix[i][j] %= 1000000007;
   }
}
return c;
}
int main()
{
    int tot, a, b, c, n;
    Mat stand = {0, 1, -1, 4};
    Mat e = {1, 0, 0, 1};
    long long f[3];
    while(scanf("%d", &n)!=EOF && n)
    {
         f[1]=4; f[2]=15;
         if (n <= 2)
         {
              printf("%lld\n",f[n]);
              continue;
         }
         Mat ans = e;
         Mat tmp = stand;
         n = n - 2;
         while(n)
         {
            if (n & 1)
            ans = Multi(ans, tmp);
            tmp = Multi(tmp, tmp);
            n >>= 1;
         }
         printf("%lld\n", ((ans.matrix[1][0]+1000000007) * f[1] + (ans.matrix[1][1]+1000000007 )* f[2]) % 1000000007);
         /*for (int i=0;i<2;i++)
         {
             for (int j=0;j<2;j++)
             printf("%lld ",ans.matrix[i][j]);
             printf("\n");
         }*/
     }
return 0;
}
bubuko.com,布布扣

 

hust 1013 Grid,布布扣,bubuko.com

hust 1013 Grid

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/chensunrise/p/3720074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!