輾轉相除,二進位制一的個數,快速冪演算法使用遞迴的相同處
阿新 • • 發佈:2018-11-06
遞迴在演算法競賽中起到了很重要的角色,就這三個演算法進行一些歸納
輾轉相除法:
//可以兩種遞迴的寫法,注意兩者的區別 int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b);//注意:在這裡一定要return,上面的return只能用一次,通過這個 //return我們可以實現一個延續,當然既然可以延續就可以在返回的 //過程中進行修改,在下面的快速冪演算法中會有提及 }
二進位制一的個數:
int bitcount(int x){ return x==0?0:bitcount(x/2)+(x&1);//x&1加括號 } //想裝大佬就寫上面程式碼,很精簡 int bitcount(int x){ if(x==0) return 0; return bitcount(x/2)+(x&1);//x為奇數時加一 } int bitcount(int x) { int res=0; while(x>0) { if(x&1) res++; x>>=1; } return 0; }
快速冪演算法:
LL mod_pow(LL a,LL b,LL mod) { int res=1; while(b>0) { if(b&1) res=res*a%mod;//如果是奇數,則執行 a=a*a%mod; b>>=1; } return res; } //上下兩個演算法實現一樣功能,演算法複雜度均為log(n) LL mod_pow(LL a,LL b,LL mod) { if(b==0) return 1; LL res=mod_pow(a*a%mod,b/2,mod); if(b&1) res=res*a%mod; return res;//這裡是不是和上面演算法的程式碼很像呢 //他們都是先遞迴到最深處,然後返回的時候可以進行相應返回值的修改想要實 //現這個效果,剛開始一定得if(b==0)這樣的判斷條件,其實這三個演算法特別像!!! }
再插入點當自己的筆記(可以忽略):
素數常用程式碼:
LL ol(LL x)//尤拉定理:降冪定理,
{//該函式用來返回與x在(1,x-1)中互質的個數
int res=x;
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
res=res-res/i;
while(x%i==0)
{
x/=i;
}
}
if(x>1)
res=res-res/x;
}
return res;
}
//
void prime(int k)
{
for(int i=2;i*i<=k;i++)
{
while(k%i==0)
{
vec.push_back(i);
k/=i;
}
}
if(k>1)
vec.push_back(k);
}
樹狀陣列:
//樹狀陣列輸入的一組資料可以不存
#include "bits/stdc++.h"
#define rep(i,j,k) for(int i=j;i<=k;i++)
using namespace std;
const int maxn = 1e5+7;
int a[maxn],b[maxn];
void build(int i,int n)
{
int k=i;
while(k<=n)
{
b[k]+=a[i];
k+=k&-k;
}
}
int search(int a)
{
int sum=0;
while(a!=0)
{
sum+=b[a];
a-=a&-a;
}
return sum;
}
void change(int num,int c)
{
int cut=num-a[num];
int k=num;
while(k<=n)
{
b[k]+=cut;
k+=k&-k;
}
}
int main()
{
int n;
cin>>n;
rep(i,1,n)
cin>>a[i],build(i,n);
rep(i,1,n)
cout<<b[i]<<endl;
int a1,b1;
rep(i,1,5)
cout<<search(i)<<endl;
int ans=b[b1]-b[a1];
cout<<ans<<endl;
return 0;
}
//心血來潮在插點
//判斷long long最大儲存資料,2的62次方是可以的,63就不行了
#include "bits/stdc++.h"
using namespace std;
int main()
{
long long a;
a=pow(2,62);
cout<<a<<endl;
return 0;
}//執行結果如下,是一個19位數字的數
零點半南昌航空大學405宿舍完成!!!