zoukankan      html  css  js  c++  java
  • Codeforces Round #113 (Div. 2) Tetrahedron(滚动DP)

    Tetrahedron
    time limit per test
    2 seconds
    memory limit per test
    256 megabytes
    input
    standard input
    output
    standard output

    You are given a tetrahedron. Let's mark its vertices with letters ABC and D correspondingly.

    An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.

    You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex Dto itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).

    Input

    The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.

    Output

    Print the only integer — the required number of ways modulo 1000000007 (109 + 7).

    Examples
    input
    2
    output
    3
    input
    4
    output
    21
    Note

    The required paths in the first sample are:

    • D - A - D
    • D - B - D
    • D - C - D

    【题意】给你一个四面体,每一个顶点可以走一步到达他相邻的顶点,每一步必须走,不能停留在原地。问你从D点出发经过n步再回到

    D点的方案数是多少。

    【分析】简单DP,dp[i][j]表示第j步走到顶点i的方案数,然后用其他三个顶点更新就行了。但是...会MLE。我们发现每一种状态只与他前一步的状态有关,之前的没用了,空间浪费,所以可以考虑用滚动数组。

    #include <bits/stdc++.h>
    #define pb push_back
    #define mp make_pair
    #define vi vector<int>
    #define inf 0x3f3f3f3f
    #define met(a,b) memset(a,b,sizeof a)
    using namespace std;
    typedef long long LL;
    const int N = 1e7+5;
    const int mod = 1e9+7;
    int n;
    LL dp[4][2];
    int main(){
        scanf("%d",&n);
        dp[2][1]=dp[3][1]=dp[1][1]=1;
        for(int i=2;i<=n;i++){
            int k=i&1;
            dp[0][k]=(dp[1][k^1]+dp[2][k^1]+dp[3][k^1])%mod;
            dp[1][k]=(dp[0][k^1]+dp[2][k^1]+dp[3][k^1])%mod;
            dp[2][k]=(dp[1][k^1]+dp[0][k^1]+dp[3][k^1])%mod;
            dp[3][k]=(dp[1][k^1]+dp[2][k^1]+dp[0][k^1])%mod;
        }
        printf("%lld
    ",dp[0][n&1]);
        return 0;
    }
  • 相关阅读:
    Java并发指南3:并发三大问题与volatile关键字,CAS操作
    Java并发指南2:深入理解Java内存模型JMM
    Java并发指南1:并发基础与Java多线程
    Java集合详解8:Java集合类细节精讲,细节决定成败
    Java集合详解7:一文搞清楚HashSet,TreeSet与LinkedHashSet的异同
    Java集合详解6:这次,从头到尾带你解读Java中的红黑树
    IP电话的配置
    孤立账户
    服务器维护知识
    VB学习一
  • 原文地址:https://www.cnblogs.com/jianrenfang/p/7226177.html
Copyright © 2011-2022 走看看