妞妞的三个盒子

妞妞的三个盒子
时间限制: 1 Sec 内存限制: 128 MB

题目描述
妞妞在公园里游玩时捡到了很多小球,而且每个球都不一样。妞妞找遍了全身只发现了3个一模一样的盒子。她打算把这些小球都装进盒子里(盒子可以为空)。她想知道她总共有多少种放法。

将N个不同的球放到3个相同的盒子里,求放球的方案总数M。 结果可能很大,我们仅要求输出M mod K的结果。 现在,妞妞已经统计出了N<=10的所有情况。见下表:

N 1 2 3 4 5 6 7 8 9 10

M 1 2 5 14 41 122 365 1094 3281 9842
输入
两个整数N,K,N表示球的个数。
输出
输出仅包括一行,一个整数M mod K 。
样例输入 Copy
11 10000
样例输出 Copy
9525
提示
对于 40%数据,10<=N<=10,000;
对于100%数据,10<=N<=1,000,000,000,K<=100,000。

看给你的数据不难发现 f [ i ] = f [ i - 1 ] * 3 - 1 ,可以推出每一项为 ( 3 ^ ( n - 1 ) + 1 ) / 2 (带进去找下规律即可) 。让后还要取模,这里是除法且逆元不能直接用费马小定理得出,那么就需要用下面的公式了 (a/b)%m = (a%(b*m))/b ,就比较容易了。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

LL n,k;

LL qmi(LL a,LL b)
{
	LL res=1;
	while(b)
	{
		if(b&1) res=res*a%k;
		a=a*a%k;
		b>>=1;
	}
	return res%k;
}

int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);

	cin>>n>>k;
	
	k*=2;
	
	LL a=qmi(3,n-1);

	cout<<(((a+1)%k)/2)%k<<endl;




	return 0;
}










发布了43 篇原创文章 · 获赞 1 · 访问量 1570

猜你喜欢

转载自blog.csdn.net/DaNIelLAk/article/details/105173847