P15802 [GESP202603 七级] 拆分
题目
传送门
思路
观察样例:
- 5=2+3,而答案是 2*3=6,这也是取模后的答案。
- 8=2+3+3,而答案是 2*3^2=18,这也是取模后的答案。
- 100=22+32×3,而答案是22*3^32,取模 1e9 的答案为 755407364。
特点
我们观察到样例的每个数都有2和3,我们通过6来说明,33>22*2,你可以举其他的例子,但是,所有都是3是最优的。
如果不是3的倍数怎么办?
n<3,直接输出n
n%3=0 输出他的幂
n%3=1 乘上1是不划算的,所以我们减去一个3然后用这个一,所以我们少乘上一个3,多乘上一个4
n%3=2 输出他的幂再乘上多余的2
代码
有注释
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9;
long long n;
long long ksm(long long x,long long y){//不用快速幂会超时
long long ans=1;
while(y>0){
if(y%2==1){
y-=1;
y/=2;
ans*=x;
ans%=mod;
x*=x;
x%=mod;
}
else{
y/=2;
x*=x;
x%=mod;
}
}
return ans%mod;
}
int main(){
int t;
cin>>t;
while(t--){
cin>>n;
if(n<3)cout<<n;
else if(n%3==0)cout<<ksm(3,n/3);
else if(n%3==1)cout<<ksm(3,n/3-1)*4%mod;
else cout<<ksm(3,n/3)*2%mod;
cout<<'\n';
}
return 0;
}
无注释
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9;
long long n;
long long ksm(long long x,long long y){
long long ans=1;
while(y>0){
if(y%2==1){
y-=1;
y/=2;
ans*=x;
ans%=mod;
x*=x;
x%=mod;
}
else{
y/=2;
x*=x;
x%=mod;
}
}
return ans%mod;
}
int main(){
int t;
cin>>t;
while(t--){
cin>>n;
if(n<3)cout<<n;
else if(n%3==0)cout<<ksm(3,n/3);
else if(n%3==1)cout<<ksm(3,n/3-1)*4%mod;
else cout<<ksm(3,n/3)*2%mod;
cout<<'\n';
}
return 0;
}

浙公网安备 33010602011771号