• hust 1013 Grid


    题目描述

    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]

    #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
    ",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
    ", ((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("
    ");
             }*/
         }
    return 0;
    }
    至少做到我努力了
  • 相关阅读:
    Struts2拦截器的底层实现(AOP思想)
    JFreeChart的使用
    struts2与servlet的耦合
    谷歌地图:使用多边形自动形成类PolygonCreator
    struts2 中的 addActionError 、addFieldError、addActionMessage方法的区别
    Struts2的声明式异常处理
    Java synchronized 详解
    [转载]C# 编写SQL SERVER 2005 的存储过程
    调试基于clr管理的sqlserver存储过程
    sqlserver中调用.net中的dll
  • 原文地址:https://www.cnblogs.com/chensunrise/p/3720074.html
Copyright © 2020-2023  润新知