目录
基础算法
整数二分
bool check(int x) //检查x是否满足某种性质
int l = 1, r = n, ans = 0;
while(l <= r)
{
int mid = (l+r)>>1;
if(check(mid)) { ans = mid; r = mid - 1; }
else l = mid + 1;
}
printf("%d", ans);
浮点数二分
bool check(double x) //检查x是否满足某种性质
double l = 1, r = n;
while(l + eps < r)
{
double mid = (l+r)/2;
if(check(mid)) r = mid;
else l = mid;
}
printf("%lf", l);
//或者写成这样
double l = 1, r = n;
for(int i=1; i<=100; i++)
{
double mid = (l+r)/2;
if(check(mid)) r = mid;
else l = mid;
}
printf("%lf", l);
归并排序
void merge_sort(int q[], int l, int r)
{
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while(i<=mid && j<=r)
{
if(q[i] <= q[j]) tmp[k++] = q[i++];
else tmp[k++] = q[j++];
}
while(i <= mid) tmp[k++] = q[i++];
while(j <= r) tmp[k++] = q[j++];
for (i=l, j=0; i<=r; i++) q[i] = tmp[j++];
}
蒙哥马利快速幂取模算法
void merge_sort(int q[], int l, int r)
{
typedef long long ll;
ll montgomery(ll a, ll b, ll c)
{
ll ans = 1;
a = a % c;
while(b > 0)
{
if(b & 1) ans = (ans * a) % c;
b = b >> 1;
a = a * a % c;
}
return ans;
}
前缀和
主要用于求数列区间和的问题,是一种重要的预处理方式
#include <bits/stdc++.h>
using namespace std;
//a为原数组,s为前缀和
int a[10] = {}, s[10] = {};
int main()
{
for(int i=1; i<=5; i++)
{
scanf("%d", &a[i]);
s[i] = s[i-1] + a[i];
}
int l = 2, r = 4;
//求a数组区间[l,r]的和
int ans = s[r] - s[l-1];
printf("%d", ans);
return 0;
}
标签:int,ll,基础,mid,算法,ans,check,模板
From: https://www.cnblogs.com/mz-xs/p/18249291