一、递推与递归的简单应用
1、多项式型枚举:
一般遍历方式:循环(for)、递推。
状态空间规模:nk,几重循环k就是几。
此种枚举十分的常见。
2、指数型枚举:
一般遍历方式:递归、位运算。
状态空间规模:kn。
例如:从1~n(n<20)个整数中随机选取任意个,输出所有可能的方案。
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
vector<int> chosen;
int n;
void solve(int x){
if(x == n+1){
for(int i=0;i<chosen.size();i++)
printf("%d ",chosen[i]);
puts("");
return ;
}
solve(x+1);
chosen.push_back(x);
solve(x+1);
chosen.pop_back();
}
int main(){
cin>>n;
solve(1);
return 0;
}
3、组合型枚举:
一般遍历方式:递归、剪枝。
状态空间规模:
(
n
m
)
\tbinom{n}{m}
(mn)。
4、排列型枚举:
一般遍历方式:递归。
状态空间规模:n!。
例如:把1~n这n个整数排成一行,输出所有可能的次序。
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
int n;
int order[20];
bool chosen[20];
void solve(int k){
if(k == n+1){
for(int i=1; i<=n; i++)
printf("%d ",order[i]);
puts("");
return;
}
for(int i=1; i<=n; i++){
if(chosen[i]) continue;
order[k]=i;
chosen[i]=1;
solve(k+1);
chosen[i]=0;
}
}
int main(){
cin>>n;
solve(1);
return 0;
}
5、习题:
费解的开关(CH0201):(https://blog.csdn.net/tirion_chenrui/article/details/88087560)
Strange Towers of Hanoi(POJ1958)(https://blog.csdn.net/tirion_chenrui/article/details/88087649)
二、分治
例题Sumdiv(POJ1845):
求AB的所有约数之和mod 9901(1<=A,B<=5e7).
题解:A的质因数分解形式为:A=p1c1p2c2……pncn,那么AB的所有约数之和就是(1+p1+p12+……+p1Bc1)(1+p2+p22+……+p2Bc2)……(1+pn+pn2+……+pnBcn).
求等比数列的和sum(p,c)=1+p+p2+…+pc对9901取模,取模的运算对除法没有分配率之类的性质,一种思路是用逆元计算,另一种思路可以使用分治法求解。
若c为奇数,
sum(p,c)
=(1+p+…+p(c-1)/2)+(p(c+1)/2+…+pc)
=(1+p(c+1)/2)*sum(p,(c-1)/2);
若c为偶数,
sum(p,c)=(1+pc/2)*sum(p,c/2-1)+p^c;
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int P = 9901;
const int maxn = 5e7+10;
ll p[50005];
int prime[50005];
ll A,B;
void isprime(){
int cnt=0,i,j;
memset(prime,0,sizeof(prime));
for(i=2;i<50005;i++){
if(prime[i]==0){
p[++cnt]=i;
for(j=2*i;j<50005;j=j+i){
prime[j]=1;
}
}
}
}
ll multi(ll A,ll B){
ll b=0;
while(B){
if(B&1){
b=(b+A)%P;
}
B=B>>1;
A=(A+A)%P;
}
return b;
}
ll pow(ll A,ll B){
ll b=1;
while(B){
if(B&1){
b=multi(b,A);
b%=P;
}
B=B>>1;
A=multi(A,A);
A%=P;
}
return b%P;
}
ll sum(ll p,ll c){
if(c==0)
return 1;
else if(c%2==1){
ll ant1=(1+pow(p,(c+1)/2));
ant1%=P;
ll ant2=sum(p,(c-1)/2);
ant2%=P;
ant1=ant1*ant2;
ant1%=P;
return ant1;
}
else {
ll ant1=(1+pow(p,c/2));
ant1%=P;
ll ant2=sum(p,c/2-1);
ant2%=P;
ll ant3=pow(p,c);
ll ant=(ant1*ant2%P+ant3%P)%P;
return ant;
}
}
int main(){
cin>>A>>B;
isprime();
ll ans = 1;
for(int i=1;p[i]*p[i]<=A;i++){
if(A%p[i]==0){
int num=0;
while(A%p[i]==0){
num++;
A=A/p[i];
}
ans=((ans%P)*(sum(p[i],B*num)%P))%P;
}
}
if(A>1){
ans=((ans%P)*(sum(A,B)%P))%P;
}
cout<<ans<<endl;
return 0;
}
三、分形
例题:POJ3889(待补充)