各种算法杂记,从“入门”的到“提高”“省选”的,应有尽有!这些算法,我从小学到大!
代码
1.基础代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
return 0;
}
2.二进制=>十进制
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int n=0,len=s.length();
for(int i=0;i<len;++i){
//其中注意if的判断两个条件相等的符号
if(s[i]=='1') n+=pow(2,len-1-i); //i2^i
}
cout<<n;
return 0;
}3.bfs 广度优先搜索
#include<bits/stdc++.h>
#define ll int
using namespace std;
const int N=4e2+10;
bool vis[N][N];//这个点是否被走过
ll step[N][N],n,m;//到这个点的步数
ll dir[][2]={{-1,2},{-1,-2},{1,2},{1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
bool isvalid(ll x,ll y){return x>=1 && x<=n && y>=1 && y<=m;}
struct node{ll x,y;};//可以加更多变量
void bfs(ll x,ll y){
queue<node> q;
q.push(node{x,y});
vis[x][y]=1;step[x][y]=0;
while(q.size()){
node tp=q.front();q.pop();
for(ll i=0;i<8;i++){
ll dx=tp.x+dir[i][0],dy=tp.y+dir[i][1];//可以走的方向的x,y
if(!isvalid(dx,dy)) continue;
if(vis[dx][dy]) continue;
vis[dx][dy]=1,step[dx][dy]=step[tp.x][tp.y]+1;
q.push(node{dx,dy});
}
}
for(ll i=1;i<=n;i++){
for(ll j=1;j<=m;j++){
ll w=step[i][j];
if(i==x && j==y) cout<<0<<" ";
else cout<<(w==0 ? -1: w) <<" \n"[j==n];//输出
}
}
}
int main(){
ll x,y;
cin>>n>>m>>x>>y;
bfs(x,y);
return 0;
}4.dfs 深度优先搜索
// k 表示当前在 第几层for循环
void dfs(int x, int y) {
if (???到了某个状态) {
执行什么操作???
return ;
}
这个状态能引申到什么状态
for (int i = 0; i < 4; i++) {
int dx = x + dir[i][0], dy = y + dir[i][1];
限制??
if (!isValid(dx, dy)) continue ;
if (vis[dx][dy]) continue ;
if (a[dx][dy]) continue ;
是否需要标记????
vis[dx][dy] = 1;
dfs(dx, dy);
是否需要取消表示??? 回溯
vis[dx][dy] = 0;
}
}
5.预处理 快速幂
#include<bits/stdc++.h>
#define ll long long
using namespace std;
//ll npow(ll x,ll y,ll p){ 快速幂 x的y次方的%p
// ll res=1;
// x%=p;
// while(y){
// if(y&1) res=res*x%p;
// y>>=1,x=x*x%p;
// }
// return res%p;
//}
const int N=3e6+10;
ll inv[N],fact[N],invfact[N],n,p;
int main(){
cin>>n>>p;
inv[0]=1,inv[1]=1;fact[0]=1,fact[1]=1;
cout<<1<<"\n";
for(ll i=2;i<=n;i++){//预处理
inv[i]=1ll*(p-p/i)*inv[p%i]%p;
fact[i]=fact[i-1]*i%p;
invfact[i]=invfact[i-1]*invfact[i]%p;
cout<<inv[i]<<"\n";
}
return 0;
}6.卢卡斯算法
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e5+10;
ll inv[N],fact[N],invfact[N],t;
ll C(int n,int m,ll p){
if(m>n) return 0;
return fact[n]*invfact[m]%p*invfact[n-m]%p;
}
ll lucas(int n,int m,ll p){
if(m==0) return 1;
return C(n%p,m%p,p)*lucas(n/p,m/p,p)%p;
}
int main(){
inv[0]=inv[1]=1;
fact[0]=fact[1]=1;
invfact[0]=invfact[1]=1;
cin>>t;
while(t--){
int n,m;ll p;
cin>>n>>m>>p;
for(ll i=2;i<=p;i++){
inv[i]=(p-p/i)*inv[p%i]%p;
fact[i]=fact[i-1]*i%p;
invfact[i]=invfact[i-1]*inv[i]%p;
}
cout<<lucas(n+m,n,p)<<"\n";
}
return 0;
}7.并查集
void init(int n){for(int i=0;i<=n;i++) f[i]=i;}//初始化
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}//查
void merge(int x,int y) {//并
int fx=find(x),fy=find(y);
if(fx==fy) return ;
f[fx]=fy;
}
bool isSame(int x,int y){return find(x)==find(y);}//集
bool isPar(int x){return x==find(x);}//为根?8.快读+快输(正在开发)
int in()
{
int k=0,f=1;
char c=getchar_unlocked();
while(c<'0'||c>'9')
{
if(c=='-')f=-1;
c=getchar_unlocked();
}
while(c>='0'&&c<='9')k=k*10+c-'0',c=getchar_unlocked();
return k*f;
}
void out(int x)
{
if(x<0)putchar('-'),x=-x;
if(x<10)putchar(x+'0');
else out(x/10),putchar(x%10+'0');
}9.ST表
#include<bits/stdc++.h>
#define ll int
using namespace std;
const int N=1e5+10;
ll dp[N][25];//从i开始 长度为pow(2,j)的区间的性质
ll a[N],LOG2[N];//LOG2 i的对数向下取整 O(1)
ll query(ll l,ll r){
if(l>r) return 0;
ll k=LOG2[r-l+1];//pow(2,k)=len max(k)
return max(dp[l][k],dp[r-(1<<k)+1][k]);//区间的max
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);//关闭信息流
LOG2[0]=-1;
for(ll i=1;i<N;i++) LOG2[i]=LOG2[i>>1]+1;
ll n,m;cin>>n>>m;
for(ll i=1;i<=n;i++){cin>>a[i];dp[i][0]=a[i];}
for(ll j=1;j<=24;j++){
for(ll i=1;i+(1<<j)-1<=n;i++){
dp[i][j]=max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
}
}
for(ll i=1;i<=m;i++){
ll l,r;cin>>l>>r;
cout<<query(l,r)<<"\n";
}
return 0;
}10.dijkstra算法(优化)
#include<bits/stdc++.h>
#define ll int
using namespace std;
ll n,m;
struct node{
ll u,w;//到 u 这个点的距离是 w
bool operator<(const node& others) const{return w>others.w;}//运算符存在 比较 struct 之间的大小
};
struct edge{
ll v,w;//去 v 这个点的权值是 w
};
const ll N=1e5+10;
vector<edge> edges[N];
ll dis[N],vis[N];
void dijkstra(ll s){//s 起点
priority_queue<node> pq;//优先队列里< 和 > 相反 默认从小到大
memset(dis,0x3f,sizeof dis);
dis[s]=0;
pq.push(node{s,0});
while(pq.size()){
node tp=pq.top();
pq.pop();
ll u=tp.u;
if(vis[u]) continue;
vis[u]=1;
for(edge tmp: edges[u]){//更新从 u 出发能去的所有点
ll v=tmp.v,w=tmp.w;
if(dis[u]+w<dis[v]){
dis[v]=dis[u]+w;
pq.push(node{v,dis[v]});
}
}
}
}
int main(){
ll n,m,s;cin>>n>>m>>s;
for(ll i=1;i<=m;i++){
ll u,v,w;cin>>u>>v>>w;
edges[u].push_back({v,w});//从 v 出发 能去 v,权值是 w
}
dijkstra(s);
for(ll i=1;i<=n;i++){
cout<<dis[i]<<" \n"[i==n];
}
return 0;
}
10.前缀和 差分(一二维)
s为差分数组,a为输入数组
10.1.一维
s[i]=s[i-1]+a[i];10.2.二维
10.2.1.前缀和
s[x][y]=s[x][y-1]+s[x-1][y]-s[x-1][y-1]+a[x][y]10.2.2.差分
a[x][y]=s[x][y]-(s[x][y-1]+s[x-1][y]-s[x-1][y-1]+a[x][y])
=(s[x][y]+s[x-1][y-1])-(s[x][y-1]+s[x-1][y])
将x,y -> xx,yy +1
a[x][y]+v;
a[x][yy+1]-v;
a[xx+1][y]-v;
a[xx+1][yy+1]+v;10.2.3.求子矩阵
求x,y到xx,yy的和
s[xx][yy]-s[xx][y-1]-s[x-1][yy]+um[x-1][y-1];11.二分答案
#include<bits/stdc++.h>
#define ll int
using namespace std;
const ll N=1e5+10,M=1e8;
ll a[N],k,n;
ll cal(ll x){//检查
long long sum=0;
for(ll i=1;i<=n;i++){
//条件
}
return 1;//true or false
}
int main(){
cin>>n>>k;
for(ll i=1;i<=n;i++) cin>>a[i];
ll l=1,r=M,ans=0;
while(l<=r){
ll mid=(l+r)/2;//二分
if(cal(mid)) ans=mid,l=mid+1;//右
else r=mid-1;//左
}
cout<<ans;
return 0;
}
12.string自带函数
1.str.c_str() 返回对应于字符串内容的C风格零结尾的只读字符串
例:printf("%s",s.c_str);
2.str.substr(a,b) 获取字符串内容中以a为起点长度为b的子串(b默认为从a到字符串末尾的字符数)
例:string a=s.substr(i,j-i);
3.str.size/length() 返回数据的字符长度
例:for(int i=0;i<s.size();i++)
4.str.find() 前向搜索特定子串的第一次出现
例:if(s.find()>100) cout<<cnt<<"\n";
5.str.erase(a,b) 删除字符串内容中以a为起点长度为b的子串
例:s.erase(i,j+1);
6.reverse(a,b) 反转一种单个数据类型自a至b范围的子串
例:reverse(s.begin(),s.end());
7.str.replace(a,b,string c) 替换以a为起点长度为b的子串为字符串c
例:s.replace(5,1,"Hello");13.排序算法大合集
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
void Bubble_Sort(int a[],int n){//冒泡排序 O(n^2)
for(int i=1;i<n;i++){//循环 n-1 轮,即轮数
for(int j=1;j<=n-i;j++){
if(a[j]>a[j+1]) swap(a[j],a[j+1]);
}
}
}
void Selection_Sort(int a[],int n){//选择排序 O(n^2)
a[0]=INT_MIN;//防止负数
for(int i=1;i<n;i++){
int k=i;//从 i~n 内找最小值的下标
for(int j=i+1;j<=n;j++){
if(a[j]<a[k]) k=j;
}
swap(a[i],a[k]);
}
}
void Insertion_Sort(int a[],int n){//插入排序 O(n^2)
for(int i=2;i<=n;i++){
int k=a[i],idx=i;// k 为待插入的数字, idx 为 k 的下标
while(k<a[idx-1]){
a[idx]+=a[idx-1];
idx--;
}
a[idx]=k;
}
}
void Counting_Sort(int a[],int n){//计数排序 O(n+len)
int maxn=a[1],minn=a[1];
for(int i=2;i<=n;i++){
maxn=max(maxn,a[i]);
minn=min(minn,a[i]);
}
int len=maxn-minn+1;//值域
vector<int> g(len+1,0);
for(int i=1;i<=n;i++) g[a[i]-minn]++;//计数并映射,来计负数
int ni=1;
for(int i=0;i<len;i++){
for(int j=1;j<=g[i];j++) a[ni]=i+minn,ni++;
}
}
void Merge_Array(int a[],int l,int mid,int r){//归并排序中的归并
vector<int> g;
int m=mid+1,x=l;
while(x<=mid&&m<=r){
if(a[x]<a[m]) g.push_back(a[x++]);
else g.push_back(a[m++]);
}
while(x<=mid) g.push_back(a[x++]);
while(m<=r) g.push_back(a[m++]);
for(int i=l;i<=r;i++) a[i]=g[i-l];
}
void Merge_Sort(int a[],int l,int r){//归并排序 在 [l,r] 排序 O(n log2 n)
if(l==r) return ;
int mid=l+r>>1;
Merge_Sort(a,l,mid);
Merge_Sort(a,mid+1,r);
Merge_Array(a,l,mid,r);
}
int Datum_Find(int a[],int l,int r){//以 a[l] 作为基准,将区间 [l,r] 分成左右段
int k=a[l];
while(l<r){
while(l<r&&a[r]>=k) r--;
a[l]=a[r];
while(l<r&&a[l]<=k) l++;
a[r]=a[l];
}
a[l]=k;
return l;
}
void Quick_Sort(int a[],int l,int r){//快速排序 O(n log2 n)
if(l>=r) return ;
int mid=Datum_Find(a,l,r);//基于 a[l] [l~r] 这个区间分成两段
Quick_Sort(a,l,mid-1);//左区间
Quick_Sort(a,mid+1,r);//右区间
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n,a[N];
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
Merge_Sort(a,n);
for(int i=1;i<=n;i++) cout<<a[i]<<" \n"[i==n];
return 0;
}
13.二叉树的前中后缀
#include<bits/stdc++.h>
#define ll int
using namespace std;
const int N=1e6+10;
struct nofe{int l,r;}a[N];
void dfs1(int root){//前缀
cout<<root<<" ";
if(a[root].l) dfs1(a[root].l);//遍历左子树
if(a[root].r) dfs1(a[root].r);//遍历右子树
}
void dfs2(int root){//中缀
if(a[root].l) dfs2(a[root].l);//遍历左子树
cout<<root<<" ";
if(a[root].r) dfs2(a[root].r);//遍历右子树
}
void dfs3(int root){//后缀
if(a[root].l) dfs3(a[root].l);//遍历左子树
if(a[root].r) dfs3(a[root].r);//遍历右子树
cout<<root<<" ";
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i].l>>a[i].r;
dfs1(1);
cout<<"\n";
dfs2(1);
cout<<"\n";
dfs3(1);
return 0;
}14.1 线段树
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5+10;
struct TreeNode{
int l, r;//基本信息(左右断点)
//真正维护的信息(区间和)
LL sum;
//修改需要记录的懒标记(tag)
LL taga, tagm;
}T[N<<2];
LL a[N];LL mod;
void pushup(int rt){
//将两个儿子节点的信息合并到根节点上。
T[rt].sum = T[rt<<1].sum + T[rt<<1|1].sum;
T[rt].sum %= mod;
}
void build(int rt, int l, int r){
//对当前节点的初始化操作 T[rt].xxx = 0/-1;
T[rt].l = l;T[rt].r = r;
T[rt].taga = 0;T[rt].tagm = 1;
if(l==r){
T[rt].sum = a[l];
return;
}
int mid=l+r>>1;
build(rt<<1, l, mid);
build(rt<<1|1, mid+1, r);
pushup(rt);
}
void modify(int rt, LL a, LL m){
T[rt].sum = T[rt].sum * m % mod;
T[rt].sum = (T[rt].sum + a * (T[rt].r - T[rt].l+1)%mod)%mod;
T[rt].taga = (T[rt].taga * m + a)%mod;
T[rt].tagm = T[rt].tagm * m % mod;
}
void pushdown(int rt){
modify(rt<<1, T[rt].taga, T[rt].tagm);
modify(rt<<1|1, T[rt].taga, T[rt].tagm);
T[rt].taga = 0;T[rt].tagm = 1;
}
void update(int rt, int l, int r, LL a=0, LL m=1){
if(l<=T[rt].l && T[rt].r<=r){
modify(rt, a, m);
return;
}
pushdown(rt);
int mid = T[rt].l+T[rt].r>>1;
if(l<=mid)update(rt<<1, l, r, a, m);
if(r>mid)update(rt<<1|1, l, r, a, m);
pushup(rt);
}
LL query(int rt, int l, int r){
if(l<=T[rt].l && T[rt].r<=r){
return T[rt].sum;
}
pushdown(rt);
int mid = T[rt].l+T[rt].r>>1;
LL rtn = 0;
if(l<=mid)rtn = (rtn + query(rt<<1, l, r))%mod;
if(r>mid)rtn = (rtn + query(rt<<1|1, l, r))%mod;
return rtn;
}
int n, m;
int main(){
scanf("%d%d%lld", &n, &m, &mod);
for(int i=1;i<=n;i++)scanf("%lld", a+i);
build(1, 1, n);
while(m--){
int op, l, r;LL x;
scanf("%d%d%d", &op, &l, &r);
if(op==3){
printf("%lld\n", query(1, l, r));
}else if(op==2){
scanf("%lld", &x);
update(1, l, r, x, 1);
}else{
scanf("%lld", &x);
update(1, l, r, 0, x);
}
}
return 0;
}
*/14.2 线段树(cxc版)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n, m, a[100005];
struct node{
ll l, r, data, add;
}tr[400005];
void build(ll l, ll r, ll idx){//建树
tr[idx]={l, r, 0, 0};
if(l==r){
tr[idx].data=a[l];
return;
}
ll mid=l+r>>1;
build(l, mid, idx*2);
build(mid+1, r, idx*2+1);
tr[idx].data=tr[idx*2].data+tr[idx*2+1].data;
return;
}
void pd(ll idx){//下传懒标记
ll add=tr[idx].add;tr[idx].add=0;
if(add==0)return;
tr[idx*2].data+=(tr[idx*2].r-tr[idx*2].l+1)*add;
tr[idx*2+1].data+=(tr[idx*2+1].r-tr[idx*2+1].l+1)*add;
tr[idx*2].add+=add;
tr[idx*2+1].add+=add;
return;
}
void update(ll l, ll r, ll idx, ll data){//添加
ll ln=tr[idx].l, rn=tr[idx].r;
if(l<=ln&&rn<=r){
tr[idx].data+=data*(rn-ln+1);
tr[idx].add+=data;
return;
}
ll mid=ln+rn>>1;pd(idx);
if(l<=mid)update(l, r, idx*2, data);
if(mid<r)update(l, r, idx*2+1, data);
tr[idx].data=tr[idx*2].data+tr[idx*2+1].data;
return;
}
ll query(ll l, ll r, ll idx){//查找
ll ln=tr[idx].l, rn=tr[idx].r;
if(l<=ln&&rn<=r)return tr[idx].data;
ll mid=ln+rn>>1, sum=0;pd(idx);
if(l<=mid)sum+=query(l, r, idx*2);
if(mid<r)sum+=query(l, r, idx*2+1);
return sum;
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
...
return 0;
}其他:
*AC 100%
/*
................................................................................................... ... . ... . ... . ..
................................................................................................... ... . ... . ... . ..
...................................................................................................
......... ... . ... . ..................................................................................................
....... . ... .. ..... ......................................,..............,.........................................
............. ..II,................................I,.....,IIIIII.........II+III+......~IIIII....=II,.
..................=II........IIIII+................?III:.....IIII?IIII......IIII+?III....:II~IIIIIIIIII:. .... .... ..
..................III......III..:II+............~III~II:....II=.....:II....:I?: ....II...II...?I?...=I?.................
.................7III.....II=....?II............:?...II:....I?.......II....II.......+I:..7I,.?II....II..................
............ ..,II.II....II~......?I.................II....II........II...=I:.......~I=...IIII,....II...................
..............=II..II....?I..........................II....II........II...II........II,...........II....................
.......... ..II?...II....II..........................II....II.......?I~.. II. ......?I...........II....,:...............
............IIIIIIIIII,..+II.........................II....II,.....?II....?I?.....,II...........II....IIIII.............
..........=III?,...II,.....III=...~~,................II.....II+...III......III...III...........II,...II..~II............
.........III.......III.......?IIIIII=................II.....:IIIIII.........IIIIII:............II....II...II............
........,~.. .. .I~........................................................,......................IIIIII:.... ...
....... ... .... ...............................................................................II...............
........ . .... ....................................................................................................
...... . . . ...............................................................................................
...... . . ................................................................................................
....... . ... ... ............................................................................ ... ... ...
........ . .... ....................................................................................................
...... ........................................................................... ... ... ...
*/贪吃蛇:
#include<bits/stdc++.h>
#include<cstdio>
#include<conio.h>
#include<stdlib.h>
#include<windows.h>
using namespace std;
void Set(){
HANDLE hOut;
COORD pos={0,0};
hOut=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOut,pos);
}
int y=12,x=11,high=25,wide=25,lon=-1,ji=-1,xx,yy,miao=300,hh=1;
char co;
int tx[100],ty[100] ;
bool fru;
char m[29][99]={"#########################",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# O #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"# #",
"#########################",};
void fr(){
xx=rand()%24;
yy=rand()%24;
xx++;
yy++;
lon++;
ji++;
fru=m[xx][yy]==' ';
m[xx][yy]='*';
}
void print(){
Set();
for(int i = 0; i <= 21; i++){
puts(m[i]);
}
cout <<"得分:"<<ji<<"分";
}
void cao(){
bool zhen=true;
while(1==1&&zhen==1){
miao--;
if(miao<=100){
miao=100;
}
if(_kbhit()){
co=getch();
}
switch(co){
case 'K':
case 'a':{
zhen=(m[x][y-1]==' ');
if(lon == 0){
m[x][y]=' ';
}
y--;
m[x][y]='O';
hh++;
print();
break;
}
case 'M':
case 'd':{
zhen=(m[x][y+1]==' ');
if(lon == 0){
m[x][y]=' ';
}
y++;
m[x][y]='O';
hh++;
print();
break;
}
case 'H':
case 'w':{
zhen=(m[x-1][y]==' ');
if(lon == 0){
m[x][y]=' ';
}
x--;
m[x][y]='O';
hh++;
print();
break;
}
case 'P':
case 's':{
zhen=(m[x+1][y]==' ');
if(lon == 0){
m[x][y]=' ';
}
x++;
m[x][y]='O';
hh++;
print();
break;
}
}
Sleep(miao+100/(lon+1));//等待
if(lon>0){
for(int i=lon;i>=1;i--){
tx[i]=tx[i-1];
ty[i]=ty[i-1];
m[tx[i]][ty[i]]='o';
}
m[tx[lon]][ty[lon]]=' ';
}
tx[0]=x;
ty[0]=y;
if(x==xx&&y==yy){
zhen=1;
fr();
while(fru==0){
fr();
}
}
if(hh>=100){
lon++;
hh=0;
ji++;
}
zhen=(0==(x==0||x==high-1||y==0||y==wide-1)&&zhen==1);
}
}
void xuan(int a){
if(a==1){
system("color 74"); //红
}
else if(a==2){
system("color 71"); //蓝
}
else{
system("color 72"); //绿
}
}
int main(){
xuan(3);
srand(time(NULL));
fr();
lon=0;
print();
cao();
cout << '\n';
cout << '\n';
cout << "你输了";
return 0;
}自制鼠标连点器
#include<bits/stdc++.h>
#include<windows.h>
#include<winuser.h>
//#include<chrono.h>
#include<conio.h>
//std::chrono::milliseconds interval time = std::chrono::milliseconds (500);
using namespace std;
int c;
int main(){
cin>> c ;
int a=10;
if(c==3)a=2;
while(a--){
_sleep(999);
cout<<a<<' ';
}
system("cls");
while (c--){
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
// _sleep(2);
if(_kbhit())break;
}
return 0;
}