zoukankan      html  css  js  c++  java
  • 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;
    }
    至少做到我努力了
  • 相关阅读:
    fetch与xhr的对比
    使用 fetch
    数组的剩余方法
    slice方法与splice方法
    php命名空间使用
    PHP面向对象编程学习之对象基础
    ubuntu下lamp环境配置及将window代码迁移至linux系统
    ThinkPHP中使用ajax接收json数据的方法
    给js文件传递参数
    JavaScript和php常用语法——切割字符串
  • 原文地址:https://www.cnblogs.com/chensunrise/p/3720074.html
Copyright © 2011-2022 走看看