Educational Codeforces Round 13——D. Iterated Linear Function(矩阵快速幂或普通快速幂水题)

 
D. Iterated Linear Function
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Consider a linear function f(x) = Ax + B. Let's define g(0)(x) = x and g(n)(x) = f(g(n - 1)(x)) for n > 0. For the given integer values ABn and x find the value of g(n)(x) modulo 109 + 7.

Input

The only line contains four integers ABn and x (1 ≤ A, B, x ≤ 109, 1 ≤ n ≤ 1018) — the parameters from the problem statement.

Note that the given value n can be too large, so you should use 64-bit integer type to store it. In C++ you can use thelong long integer type and in Java you can use long integer type.

Output

Print the only integer s — the value g(n)(x) modulo 109 + 7.

Examples
input
3 4 1 1
output
7
input
3 4 2 1
output
25
input
3 4 3 1
output
79


裸题一道。最近玩SPFA有点过头……矩阵快速幂做了有一段时间了,构造矩阵还想了几分钟,我也是醉了……。好像也可以用普通快速幂,把r=r*bas%mod改成r=(r*bas+b)%mod即可,一开始全部设为int各种苦逼WA……千万记得最后输出的答案再模mod,这里又苦逼WA一发……

代码:

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#define INF 0x3f3f3f3f
#define MM(x) memset(x,0,sizeof(x))
#define MMINF(x) memset(x,INF,sizeof(x))
using namespace std;
typedef long long LL;
struct mat
{
	LL pos[2][2];
	mat(){MM(pos);}
};
LL a,b,n,x;
const int mod=1e9+7;
inline mat operator*(const mat &a,const mat &b)
{
	mat c;
	for (int i=0; i<2; i++)
	{
		for (int j=0; j<2; j++)
		{
			for (int k=0; k<2; k++)
			{
				c.pos[i][j]+=(a.pos[i][k]*b.pos[k][j])%mod;
			}
		}
	}
	return c;
}
inline mat operator^(mat a,LL b)
{
	mat bas=a,r;
	for (int i=0; i<2; i++)
		r.pos[i][i]=1;
	while (b!=0)
	{
		if(b&1)
			r=r*bas;
		bas=bas*bas;
		b>>=1;
	}
	return r;
}
int main(void)
{
	while (cin>>a>>b>>n>>x)
	{
		mat one,t;
		one.pos[0][0]=x;
		one.pos[1][0]=1;
		t.pos[0][0]=a;
		t.pos[0][1]=b;
		t.pos[1][1]=1;
		t=t^(n);
		one=t*one;
		cout<<one.pos[0][0]%mod<<endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Blackops/p/5766327.html