九度 题目1442:A sequence of numbers

来源:互联网 发布:管理系统常用算法 编辑:程序博客网 时间:2024/05/17 07:34

九度 题目1442:A sequence of numbers

原题OJ链接:http://ac.jobdu.com/problem.php?pid=1442

题目描述:

Xinlv wrote some sequences on the paper a long time ago, they might be arithmetic or geometric sequences. The numbers are not very clear now, and only the first three numbers of each sequence are recognizable. Xinlv wants to know some numbers in these sequences, and he needs your help.

输入:

The first line contains an integer N, indicting that there are N sequences. Each of the following N lines contain four integers. The first three indicating the first three numbers of the sequence, and the last one is K, indicating that we want to know the K-th numbers of the sequence.
You can assume 0 < K <= 10^9, and the other three numbers are in the range [0, 2^63). All the numbers of the sequences are integers. And the sequences are non-decreasing.

输出:

Output one line for each test case, that is, the K-th number module (%) 200907.

样例输入:

21 2 3 51 2 4 5

样例输出:

516

解题思路:

这个序列只有两种:一是等差数列,一是等比数列。
两种情况都要考虑结果是否溢出,超出long long int的范围。等比数列的话应用二分求幂的思想。

源代码:

#include<iostream>using namespace std;int main(){    int N,K;    while(cin>>N){        long long int x1,x2,x3;        long long int ans;        for(int i=0;i<N;i++){            cin>>x1>>x2>>x3>>K;            if(x2-x1==x3-x2){//等差数列                int d=x2-x1;                ans=(x1%200907+(K-1)%200907*d%200907)%200907;                //ans=x1+(K-1)*d;                //ans=ans%200907;                cout<<ans<<endl;                continue;            }            if(x2/x1==x3/x2){//等比数列                long long int q=x2/x1;                ans=x1;                int p=K-1;                while(p!=0){                    if(p%2==1){                        ans*=q;                        ans%=200907;                    }                    p/=2;                    q*=q;                    q%=200907;                }                cout<<ans<<endl;            }        }    }    return 0;}