CodeForces - 226A Flying Saucer Segments 矩阵快速幂或等比数列求和

http://codeforces.com/problemset/problem/226/A

题意:有①—②—③三个点如此连接。有n个数在位置③,要全部移动到位置①。数A可以从一个点移动到另一个点,当且仅当A大于这两个点的所有数。

题解:多写几个可以发现递推式:a[n]=3*a[n-1]+2。

法一:构造矩阵进行矩阵快速幂。

| a[n] 1 |   | 3 0 |

|  0    0 |   | 2 1 |

法二:等比数列求和:a[n]+1=3*(a[n-1]+1),所以a[n]=3^n-1。


矩阵快速幂:

#include<set>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<string>
#include<bitset>

#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>

#include<iomanip>
#include<iostream>

#define debug cout<<"aaa"<<endl
#define mem(a,b) memset(a,b,sizeof(a))
#define LL long long
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define MIN_INT (-2147483647-1)
#define MAX_INT 2147483647
#define MAX_LL 9223372036854775807i64
#define MIN_LL (-9223372036854775807i64-1)
using namespace std;

const int N = 2;
LL mod;

struct node{
	LL m[N][N];
};

node Mul(node a,node b){
	node c;
	mem(c.m,0);
	for(int k=0;k<N;k++){
		for(int i=0;i<N;i++){
			if(a.m[i][k]){
				for(int j=0;j<N;j++){
					c.m[i][j]=(c.m[i][j]+(a.m[i][k]*b.m[k][j])%mod+mod)%mod;
				}
			}
		}
	}
	return c;
} 

node quickmod(node a,LL b){
	node res;
	mem(res.m,0);
	for(int i=0;i<N;i++){
		res.m[i][i]=1;
	}
	while(b){
		if(b&1){
			res=Mul(res,a);
		}
		a=Mul(a,a);
		b>>=1;
	}
	return res;
}

int main(){
	LL n;node a,b,ans;
	cin>>n>>mod;
	mem(a.m,0),mem(b.m,0); 
	b.m[0][0]=0,b.m[0][1]=1;
	a.m[0][0]=3,a.m[1][0]=2,a.m[1][1]=1;
	a=quickmod(a,n);
	ans=Mul(b,a);
	cout<<ans.m[0][0]<<endl;
	return 0;
}

等比数列:

#include<bits/stdc++.h>
#define debug cout<<"aaa"<<endl
#define d(a) cout<<a<<endl
#define mem(a,b) memset(a,b,sizeof(a))
#define LL long long
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define MIN_INT (-2147483647-1)
#define MAX_INT 2147483647
#define MAX_LL 9223372036854775807i64
#define MIN_LL (-9223372036854775807i64-1)
using namespace std;

const int N = 100000 + 5;
const int mod = 1000000000 + 7;
const double eps = 1e-8;

LL quickMod(LL a,LL b,LL m){
	LL ans=1;
	a%=m;
	while(b){
		if(b&1)
			ans=(ans*a)%m;
		a=(a*a)%m;
		b>>=1;
	}
	return ans;
} 

int main(){
	LL n,m,ans;
	cin>>n>>m;
	ans=quickMod(3,n,m)-1;
	ans=(ans+m)%m;
	cout<<ans<<endl;
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值