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;
    }
    至少做到我努力了
  • 相关阅读:
    poj 1475 Pushing Boxes 推箱子(双bfs)
    poj 1806 Frequent values(RMQ 统计次数) 详细讲解
    poj 2846 Repository
    poj Ping pong LA 4329 (树状数组统计数目)
    POJ 1962-Corporative Network (并查集)
    hdu 2217 Visit
    nyoj304 节能
    与R纠缠的两件事——rownames和子集--转载
    七步精通Python机器学习--转载
    win10专业版激活(亲测可用)
  • 原文地址:https://www.cnblogs.com/chensunrise/p/3720074.html
Copyright © 2011-2022 走看看