首页 > 代码库 > hust 1013 Grid
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\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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。