CodeForces-450B Jzzhu and Sequences【数列+矩阵快速幂】

B. Jzzhu and Sequences
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Jzzhu has invented a kind of sequences, they meet the following property:

You are given x and y, please calculate fn modulo 1000000007 (109 + 7).

Input

The first line contains two integers x and y (|x|, |y| ≤ 10^9). The second line contains a single integer n (1 ≤ n ≤ 2·10^9).

Output

Output a single integer representing fn modulo 1000000007 (10^9 + 7).

Examples
input
Copy
2 3
3
output
1
input
Copy
0 -1
2
output
1000000006
Note

In the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.

In the second sample, f2 =  - 1;  - 1 modulo (10^9 + 7) equals (10^9 + 6).


问题链接:CodeForces-450B Jzzhu and Sequences

问题简述:(略)

问题分析

  方法一:

  依据题意,fi+1=fi-fi-1。故:

  f1=x, f2=y, f3=y-x,f4=-x, f5=-y, f6=x-y, f7=x, f8=y, ......

  这个数列每6项值出现循环。

  以上分析可得到f0=f6=x-y。


  方法二:

  用矩阵快速幂实现。

程序说明

  程序中都是套路。

题记:(略)

参考链接:(略)


AC的C++语言程序(方法一)如下:

/* CodeForces-450B Jzzhu and Sequences */

#include 

using namespace std;

const int MOD = 1000000007;
const int N = 6;

int ans[N];

int main()
{
    int x, y, n;

    cin >> x >> y >> n;

    // Init ans
    ans[0] = x - y;
    ans[1] = x;
    ans[2] = y;
    ans[3] = y - x;
    ans[4] = -x;
    ans[5] = - y;

    int result = ans[n % N];
    if(result >= 0)
        cout << result % MOD << endl;
    else
        cout << (result % MOD + MOD) % MOD << endl;

    return 0;
}


AC的C++语言程序(方法二)如下:

/* CodeForces-450B Jzzhu and Sequences */

#include 
#include 

using namespace std;

typedef long long LL;

const int MOD = 1e9+7;
const int N = 2;

struct Matrix
{
    LL m[N][N];

    Matrix()
    {
        memset(m, 0, sizeof(m));
    }

    // 矩阵相乘
    Matrix operator * (const Matrix& y)
    {
        Matrix z;

        for(int i=0; i>= 1;
    }

    return z;
}

int main()
{
    int x, y, n;
    int result;

    cin >> x >> y >> n;

    if(n == 1)
        result = x;
    else if(n == 2)
        result = y;
    else {
        Matrix a;
        a.m[0][0] = 0;
        a.m[1][0] = -1;
        a.m[0][1] = a.m[1][1] =1;

        Matrix t = Matrix_Powmul(a, n - 2);

        result = (x * t.m[1][0] + y * t.m[1][1]) % MOD;
    }

    if(result >= 0)
        cout << result % MOD << endl;
    else
        cout << (result % MOD + MOD) % MOD << endl;

    return 0;
}



你可能感兴趣的:(#,ICPC-备用二,#,ICPC-CodeForces,#,ICPC-数列,#,ICPC-矩阵)