跳到正文

算法·理论

爱捷wiki(代码版)

#SUSPENDED#约 69 分钟
原文
文章信息与版本

爱捷wiki(代码版)

一篇好的wiki需要头图:

这些代码部分是作者于2023年蓝桥杯时抄写的,

作者整理了一下码风。

其他文章请点击:文章中转站

排序篇(样例代码数组大小为1005)

冒泡排序 O(n2)O(n^2)

C++
#include<bits/stdc++.h>
using namespace std;
void BubbleSort(int *a,int n){
    for(int i=0;i<n-1;i++){
        bool flag = false;
        for(int j=0;j<n-i-1;j++){
            if(a[j]>a[j+1]){
                swap(a[j],a[j+1]);
                flag = true;
            }
        }
        if(!flag) break;
    }
}
int main(){
    int n;
    cin>>n;
    int a[1005];
    for(int i=0;i<n;i++) cin>>a[i];
    BubbleSort(a,n);
    for(int i=0;i<n;i++) cout<<a[i]<<" ";
    return 0;
}

选择排序 O(n2)O(n^2)

C++
#include<bits/stdc++.h>
using namespace std;
void SelectSort(int *a,int n){
    for(int i=0;i<n;i++){
        int min = i;
        for(int j=i+1;j<n;j++)
            if(a[min]>a[j]) min=j;
        int t = a[min];a[min]=a[i];a[i]=t;
    }
}
int main(){
    int n;
    cin>>n;
    int a[1005];
    for(int i=0;i<n;i++) cin>>a[i];
    SelectSort(a,n);
    for(int i=0;i<n;i++) cout<<a[i]<<" ";
    return 0;
}

插入排序 O(n2)O(n^2)

C++
#include<bits/stdc++.h>
using namespace std;
void InsertSort(int a[],int n){
    for(int i=2;i<=n;i++){
        for(int j = i-1;a[j]>a[j+1]&&j>0;j--){
            swap(a[j],a[j+1]);
        }
    }
}
int main(){
    int a[1005],n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    InsertSort(a,n);
    for(int i=1;i<=n;i++){
        cout<<a[i]<<" ";
    }
    return 0;
}

计数排序 O(n)O(n)

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,a[1005];
    cin>>n;
    int x;
    for(int i=0;i<1005;i++){
        a[i]=0;
    }
    for(int i=0;i<n;i++){
        cin>>x;
        a[x]++;
    }
    for(int i=0;i<1005;i++){
        if(a[i]!=0){
            while(a[i]--){
                cout<<i<<" ";
            }
        }
    }
    return 0;
}

希尔排序 O(ns,1≤s≤2)O(n^s,1\le s \le 2)

C++
#include<bits/stdc++.h>
using namespace std;
void InsertSort(int a[],int n, int d){
    for(int i=d+1;i<=n;i++){
        for(int j = i-d;a[j]>a[j+d]&&j>0;j-=d){
            swap(a[j],a[j+d]);
        }
    }
}
void ShellSort(int a[],int n){
    for(int d = n/2;d>0;d/=2){
        InsertSort(a,n,d);
    }
}
int main(){
    int a[1005],n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    ShellSort(a,n);
    for(int i=1;i<=n;i++){
        cout<<a[i]<<" ";
    }
    return 0;
}

快速排序 O(nO(n loglog n)n) ~ O(n2)O(n^2)

C++
#include<bits/stdc++.h>
using namespace std;
int QuickSortOne(int a[],int low,int high){
    int k = low;
    while(low<high){
        while(low<high && a[high]>=a[k]) high--;
        while(low<high && a[low]<=a[k]) low++;
        if(low<high){
            swap(a[low],a[high]);
        }
    }
    swap(a[low],a[k]);
    return low;
}
void QuickSort(int a[],int low,int high){
    if(low<high){
        int k = QuickSortOne(a,low,high);
        QuickSort(a,low,k-1);
        QuickSort(a,k+1,high);
    }
}
int main(){
    int n;
    cin>>n;
    int a[1005];
    for(int i=0;i<n;i++) cin>>a[i];
    QuickSort(a,0,n-1);
    for(int i=0;i<n;i++) cout<<a[i]<<" ";
    return 0;
}

归并排序 O(nO(n loglog n)n)

C++
#include<bits/stdc++.h>
using namespace std;
int a[1005],b[1005];
void Merge(int low,int mid,int high){
    int i,j,k;
    for(k=low;k<=high;k++) b[k]=a[k];
    for(i=low,j=mid+1,k=low;i<=mid && j<=high;){
        a[k] = b[i]>b[j]?b[j]:b[i];
    }
    while(i<=mid) a[k++]=b[i++];
    while(j<=high) a[k++]=b[j++];
}
void MergeSort(int low,int high){
    if (low>=high) return;
    int mid = (low+high)/2;
    MergeSort(low,mid);
    MergeSort(mid+1,high);
    Merge(low,mid,high);
}
int main(){
    int n;
    cin>>n;
    for(int i=0;i<n;i++) cin>>a[i];
    MergeSort(0,n-1);
    for(int i=0;i<n;i++) cout<<a[i]<<" ";
    return 0;
}

堆排序 O(nO(n loglog n)n)

C++
#include<bits/stdc++.h>
using namespace std;
int a[1005];
int n;
void HeadAdjust(int a[],int k,int n){
    a[0]=a[k];
    for(int i = k*2;i<=n;i*=2){
        if(a[i]<a[i+1]&&i<n) i++;
        if(a[0]>=a[i]) break;
        else{
            a[k]=a[i];
            k=i;
        }
    }
    a[k]=a[0];
}
void BuildMaxHeap(int a[],int n){
    for(int i = n/2;i>0;i--){
        HeadAdjust(a,i,n);
    }
}
void HeapSort(int a[],int n){
    BuildMaxHeap(a,n);
    for(int i=n;i>1;i--){
        swap(a[1],a[i]);
        HeadAdjust(a,1,i-1);
    }
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    HeapSort(a,n);
    for(int i=1;i<=n;i++) cout<<a[i]<<" ";
    return 0;
}

数据结构篇(描述)

注:资料源于网络搜集及作者评价\tiny 注:资料源于网络搜集及作者评价

数组

连续内存空间存储相同类型元素,大小是固定的。

Vector

既能随机访问+任意扩展

话说邻接矩阵和邻接表……

链表

不能随机访问,可是插入删除O(1)O(1)诶。(话说list的bug很少吧)

哈希表

一种传奇的能将查找做到O(1)O(1)的数据结构。

Queue

FIFO,不能随机访问,还是给bfs吧。

Stack

LIFO,同样不能随机访问,还是给dfs吧。

Deque

可随机访问,不然和上面两家一样了。

数据结构篇(时间复杂度)

操作数组Vector链表哈希表QueueStackDeque
访问元素O(1)O(1)O(1)O(1)O(n)O(n)O(1)O(1)O(n)O(n)O(n)O(n)O(1)O(1)
头部插入O(n)O(n)O(n)O(n)O(1)O(1)O(1)O(1)--O(1)O(1)
尾部插入O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)
中间插入O(n)O(n)O(n)O(n)O(1)O(1)----
头部删除O(n)O(n)O(n)O(n)O(1)O(1)-O(1)O(1)-O(1)O(1)
尾部删除O(1)O(1)O(1)O(1)O(1)O(1)--O(1)O(1)O(1)O(1)
中间删除O(n)O(n)O(n)O(n)O(1)O(1)----
查找元素O(n)O(n)O(n)O(n)O(n)O(n)O(1)O(1)O(n)O(n)O(n)O(n)O(n)O(n)

数据结构篇(缺点)

数组

很明显的缺点:容易空间浪费。

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    int arr[100005];
    cin>>arr[0]>>arr[1]>>arr[2];
    cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<"\n";
    return 0;
}

Vector

没有auto的就只能写长点了。

C++
std::vector<int>::iterator t=upper_bound(vec.begin(),vec.end(),value);

链表

不能随机访问

万一搞出来野指针……

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    while(1){
        int *p;
        free(p);
    }
    return 0;
}

哈希表

冲突问题

一个好的哈希表应当是这样的:

哈希表
信息
信息
信息
信息
信息
信息
信息
信息……

一个非常不好的哈希表是这样的:

哈希表哈希表哈希表哈希表哈希表哈希表哈希表……
信息→链→信息链→信息链→信息链→信息链→信息链……

Queue&Stack&Deque

Queue和Stack不能随机访问

见上复杂度分析又可得知

Deque的属性比Queue和Stack好的多

那么为什么还会有Queue和Stack捏?

当然是因为常数巨大捏:

Deque\Huge Deque Queue stack\tiny Queue\ stack

多开点就可以……

#1#2#3#4#5#6#7#8#9#10
TLETLETLETLETLETLETLETLETLETLETLETLETLETLETLETLETLETLETLETLE

模板篇

快读

C++
inline int read() {
	int x = 0, f = 1;
	char ch = getchar();
	while (ch < '0' || ch > '9') {
		if (ch == '-')f = -1;
		ch = getchar();
	}
	while (ch <= '9' && ch >= '0')x = (x << 1) + (x << 3) + (ch ^ 48),ch = getchar();
	return x * f;
}

快写

C++
inline void write(int x) {
	if (x < 0) {
		putchar('-');
		x = -x;
	}
	int f[100001], ans = 0;
	while (x) {
		f[++ans] = x % 10 + '0';
		x /= 10;
	}
	while (ans > 0)
		putchar(f[ans--]);
	putchar('\n');
}

邻接矩阵

C++
int a[N][N];
for(int i=1;i<=n;i++){
    int x,y;
    cin>>x>>y;
    a[x][y]=1/*权值*/;
    a[y][x]=1/*权值*/;
}

vector邻接表存图

C++
vector<int>g[N];
for(int i=1;i<n;i++){
    cin>>u>>v;
    g[u].push_back(v);
    g[v].push_back(u);
}

快速幂

C++
#include<bits/stdc++.h>
using namespace std;
int qmi(int a,int b,int mod){
	int ans=1;
	while(b){
		if(b&1){
			ans*=a;
			ans%=mod;
		}
		a=a*a%mod;
		b>>=1;
	}
	return ans;
}
int main(){
	int a,b,mod;
	cin>>a>>b>>mod;
	cout<<qmi(a,b,mod);
	return 0;
}

龟速乘

代码
while(b){
		if(b&1)ans=(ans+a)%p;
		a=(a+a)%p;
		b=b>>1;
}

矩阵快速幂

C++
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN=1000;
const int Mod=1e9+7;
long long n,k;
struct Node{
	long long mx[MAXN][MAXN];
}a,b,s;
Node operator *(const Node &a,const Node &b){
	Node c;
	memset(c.mx,0,sizeof(c.mx));
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			for(int p=1;p<=n;p++)
				c.mx[i][j]=(c.mx[i][j]+(b.mx[i][p]*a.mx[p][j])%Mod)%Mod;
	return c;
}
int main(){
	cin>>n>>k;
	for(int i=1;i<=n;i++)s.mx[i][i]=1;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			cin>>a.mx[i][j];
	while(k){
		if(k&1)s=s*a;
		a=a*a;
		k>>=1;
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cout<<s.mx[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
}

单向链表

C++
#include<bits/stdc++.h>
#include<cstdio>
#define endl '\n'
#define int long long

const int N = 1e4 + 10;

using namespace std;

struct node{
	int date;
	struct node* next;
};

node* head=new node;

void add(int x,int y){
	node* p=new node;
	p->date=y;
	p->next=NULL;
	node* q=head;
	while(q!=NULL){
		if(q->date==x){
			p->next=q->next;
			q->next=p;
			break;
		}
		q=q->next;
	}
}

int ask(int x){
	node* q=head;
	while(q!=NULL){
		if(q->date==x){
			if(q->next!=NULL){
				return q->next->date;
			}
			else return 0;
		}
		q=q->next;
	}
}

void del(int x){
	node* q=head;
	while(q!=NULL){
		if(q->date==x){
			//node* r=q->next;
			q->next=q->next->next;
			//free(r);
			return;
		}
		q=q->next;
	}
}

signed main(){

	head->date=1;
	head->next=NULL;
	int n;
	cin>>n;
	while(n--){
		int op;
		cin>>op;
		if(op==1){
			int x,y;
			cin>>x>>y;
			add(x,y);
		}
		else if(op==2){
			int x;
			cin>>x;
			cout<<ask(x)<<endl;
		}
		else{
			int x;
			cin>>x;
			del(x);
		}
	}

	return 0;
}

双向链表

C++
#include<bits/stdc++.h>
#include<cstdio>
#define endl '\n'
#define int long long

const int N = 1e4+10;

using namespace std;

struct node{
    int data;
    struct node* next;
    struct node* prev;
};

int n,qs;
int len;

node* head=new node;

void addl(int x,int y){
    node* p=new node;
    p->data=x;
    p->next=NULL;
    p->prev=NULL;
    node* q =head;
    while(q!=NULL){
        if(q->data==y){
            if(q->prev!=NULL)
                q->prev->next=p;
            p->next=q;
            p->prev=q->prev;
            q->prev=p;
            break;
        }
        q=q->next;
    }
}
void addr(int x,int y){
    node* p=new node;
    p->data=x;
    p->next=NULL;
    p->prev=NULL;
    node* q=head;
    while(q!=NULL){
        if(q->data==y){
            if(q->next!=NULL)
                q->next->prev=p;
            p->next=q->next;
            p->prev=q;
            q->next=p;
            break;
        }
        q=q->next;
    }
}
void init(){
    head->data=1;
    head->next=NULL;
    head->prev=NULL;
    for(int i=2;i<=n;i++) addr(i,i-1);
}

void del(int x){
    node* q=head;
    while (q!=NULL){
        if (q->data==x){
            node* r=q;
            if(q->prev!=NULL)
                q->prev->next=q->next;
            if(q->next!=NULL)
                q->next->prev=q->prev;
            free(q);
            return;
        }
        q=q->next;
    }
}

signed main(){

	cin>>n>>qs;
	len=n;
    init();
    while(qs--){
        int op,x,y;
        cin>>op;
        if(op==1){
            cin>>x>>y;
            if(x==y)continue;
            del(x);
            addl(x,y);
        }
        else if(op==2){
            cin>>x>>y;
            if(x==y)continue;
            del(x);
            addr(x,y);
        }
        else if(op==3){
            int x;
			cin>>x;
            del(x);
            len--;
        }
    }
    if(len<=0){
    	cout<<"Empty!"<<endl;
		return 0;
	}
    node* q=head;
    while(q!=NULL){
        cout<<q->data<<" ";
        q=q->next;
    }

	return 0;
}

分解质因数

C++
#include<bits/stdc++.h>
const int N = 1e7 + 10, M = 1e5 + 10;
using namespace std;
bool st[N];
int primes[N];
int cnt, n;
int fact[N];
void get_primes() {
    for (int i = 2;i <= n;i++) {
        if (!st[i]) primes[cnt++] = i;
        for (int j = 0;i * primes[j] <= n;j++) {
            st[primes[j] * i] = true;
            fact[primes[j] * i] = primes[j];
            if (i % primes[j] == 0) break;
        }
    }
}
int main() {
    n = 10000000;
    int t;
    cin >> t;
    get_primes();
    while (t--) {
        int a; cin >> a;
        while (fact[a] > 1) {
            int t = fact[a];
            int cnt = 0;
            while (a % t == 0) a /= t, cnt++;
            cout << t << " " << cnt << endl;
        }
        if (a > 1) cout << a << " " << 1 << endl;
        cout << "-----------------" << endl;
    }

    return 0;
}

线性筛

C++
void get() {
    for (int i = 2;i <= n;i++) {
        if (!st[i]) primes[cnt++] = i;
        for (int j = 0;i * primes[j] <= n;j++) {
            st[primes[j] * i] = true;
            fact[primes[j] * i] = primes[j];
            if (i % primes[j] == 0) break;
        }
    }
}

埃氏筛

C++
void get() {
    for (int i = 2;i <= n;i++) {
        if (st[i] == 1)continue;
        for (int j = i + i;j <= n;j += i) {
            st[j] = 1;
            // if (fact[j] == 0) fact[j] = i;
            fact[j] = min(fact[j], i);
        }
    }
}

暴力筛

C++
void get() {
    for (int i = 2;i <= n;i++) {
        for (int j = i + i;j <= n;j += i) {
            st[i] = 1;
            fact[j] = min(fact[j], i);
        }
    }
}

字符串哈希

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
#define mod 998244353
using namespace std;
const int N=1e6+6,inf=2e18;
typedef pair<int,int>PII;
const int MAXN=10010;
const int jz=21133;
char s[MAXN];
int n,a[MAXN];
int h(char c[]){
	int len=strlen(c);
	int ans=0;
	for(int i=0;i<len;i++)
		ans=(ans*jz+(int)s[i])%mod;
	return ans;
}
signed main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		scanf("%s",s);
		a[i]=h(s);
	}
	sort(a+1,a+n+1);
	int ans=0;
	for(int i=2;i<=n;i++)
		if(a[i]!=a[i-1])ans++;
	cout<<ans+1;
	return 0;
}

树状数组(单点修改,区间查询)

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
const int N=1e6+6;
int m,n,q,x,y,ans,a[N],c[N];
int lowbit(int x){
	return x&-x;
}
int query(int x){
	int ans=0;
	for(int i=x;i>0;i-=lowbit(i))
		ans+=c[i];
	return ans;
}
void add(int x,int k){
	for(int i=x;i<=n;i+=lowbit(i))
		c[i]+=k;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i+=1){
		int t;
		cin>>t;
		add(i,t);
	}
	while(m--){
		cin>>q>>x>>y;
		if(q==1)
			add(x,y);
		if(q==2)
			cout<<query(y)-query(x-1)<<endl;
	}
	return 0;
}

树状数组(区间修改,单点查询)

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
const int N=1e6+6;
int m,n,q,x,y,ans,a[N],c[N];
int lowbit(int x){
	return x&-x;
}
int query(int x){
	int ans=0;
	for(int i=x;i>0;i-=lowbit(i))
		ans+=c[i];
	return ans;
}
void add(int x,int k){
	for(int i=x;i<=n;i+=lowbit(i))
		c[i]+=k;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;++i){
		cin>>a[i];
		add(i,a[i]-a[i-1]);
	}
	while(m--){
		int op;
		cin>>op;
		if(op==1){
			int l,r,k;
			cin>>l>>r>>k;
			add(l,k);
			add(r+1,-k);
		}
		else{
			int x;cin>>x;
			cout<<query(x)<<endl;
		}
	}
	return 0;
}

二维树状数组

C++
#include <cstdio>
#define lowbit(x) (x&(-x))
using namespace std;

int n = 100 , m = 100;
int qwq[105][105];

void add(int x , int y , int k){
	for(int i = x;i <= n;i += lowbit(i))
    	for(int j = y;j <= m;j += lowbit(j))
        	qwq[i][j] += k;
}

int getsum(int x , int y){
    int ans = 0;
    for(int i = x;i >= 1;i -= lowbit(i))
        for(int j = y;j >= 1;j -= lowbit(j))
        	ans += qwq[i][j];
    return ans;
}

int main(void){
	add(1 , 1 , 1);
	add(1 , 2 , 2);
	printf("%d\n" , query(1 , 2));
}

KMP

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
#define mod 998244353
using namespace std;
const int N=1e6+6;
int kmp[N],la,lb,j;
string a,b,A,B;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>A>>B;
	a='\0'+A,b='\0'+B;
	la=a.size()-1,lb=b.size()-1;
	for(int i=2;i<=lb;i++){
		while(j&&b[i]!=b[j+1])
			j=kmp[j];
		if(b[j+1]==b[i])
			j++;
		kmp[i]=j;
	}
	j=0;
	for(int i=1;i<=la;i++){
		while(j>0&&b[j+1]!=a[i])
			j=kmp[j];
		if(b[j+1]==a[i]) j++;
		if(j==lb){
			cout<<i-lb+1<<endl;
			j=kmp[j];
		}
	}
	for(int i=1;i<=lb;i++)
		cout<<kmp[i]<<" ";
	return 0;
}

并查集

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
const int N=1e6+6;
int n,m,z,x,y,p[N];
int fi(int x){
	if(x!=p[x])p[x]=fi(p[x]);
	return p[x];
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++)p[i]=i;
	while(m--){
		cin>>z>>x>>y;
		if(z==1){
			x=fi(x);
			y=fi(y);
			p[y]=x;
		}
		else{
			x=fi(x);
			y=fi(y);
			if(x!=y)cout<<"N"<<endl;
			else cout<<"Y"<<endl;
		}
	}
	return 0;
}

堆

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=9e6+6;
int a[N],m,n,si;
void doun(int u){
	int t=u;
	if(a[u*2]<a[t]&&u*2<=si)t=u*2;
	if(u*2+1<=si&&a[u*2+1]<a[t])t=u*2+1;
	if(t!=u){
		swap(a[t],a[u]);
		doun(t);
	}
}
void up(int u){
	int t=u;
	if(u/2>=1&&a[t]<a[u/2]){
		t=u/2;
	}
	if(t!=u){
		swap(a[t],a[u]);
		up(t);
	}
}
signed main(){
    cin>>n;
    while(n--){
    	int op;
    	cin>>op;
    	if(op==1){
    		int x;
    		cin>>x;
    		a[++si]=x;
    		up(si);
		}
		else if(op==2){
			cout<<a[1]<<endl;
		}
		else if(op==3){
			swap(a[1],a[si]);
			si--;
			doun(1);
		}
	}
	return 0;
}

单调栈

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=9e6+6;
int n,a[N],ans[N];
stack<int>s;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++){
    	cin>>a[i];
	}
	for(int i=n;i>=1;i--){
		while(s.size()&&a[i]>=a[s.top()])s.pop();
		if(s.size())ans[i]=s.top();
		else ans[i]=0;
		s.push(i);
	}
	for(int i=1;i<=n;i+=1)cout<<ans[i]<<" ";
	return 0;
}

最小生成树

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
#define mod 998244353
using namespace std;
const int N=1e6+6;
typedef pair<int,int>PII;
inline int read(){
	int s=0,w=1;
	char c=getchar();
	while(c<48||c>57){
		if(c=='-') w=-1;
		c=getchar();
	}
	while(c>=48&&c<=57)s=(s<<1)+(s<<3)+c-48,c=getchar();
	return s*w;
}
int n,m,p[N],sz[N],cnt,res;
array<int,3>a[N];
int find(int x) {
	if (x != p[x]) p[x] = find(p[x]);
	return p[x];
}
signed main() {
	cin.tie(0)->sync_with_stdio(0);
	cout.tie(0);
	cin >> n >> m;
	for (int i = 1;i <= n;i++) p[i] = i;
	for (int i = 1;i <= m;i++) {
		int u, v, w;
		cin >> u >> v >> w;
		a[i] = { w,u,v };
	}
	sort(a + 1, a + 1 + m);
	for (int i = 1;i <= m;i++) {
		int w = a[i][0], u = a[i][1], v = a[i][2];
		u = find(u), v = find(v);
		if (u == v) continue;
		res += w;
		p[u] = p[v];
		cnt++;
	}
	if (cnt == n - 1) cout << res << endl;
	else cout << "orz" << endl;
}

拓扑排序

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
const int N=1e3+6;
vector<int>g[N];
int d[N],n,a;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
	for (int i = 1;i <= n;i++) {
		int a;
		while (cin >> a) {
			if (a == 0) break;
			g[i].push_back(a);
			d[a]++;
		}
	}
	queue<int>q;
	for (int i = 1;i <= n;i++) {
		if (d[i] == 0) q.push(i);
	}
	while (q.size()) {
		int t = q.front();
		q.pop();
		cout << t << " ";
		for (auto it : g[t]) {
			if (--d[it] == 0) q.push(it);
		}
	}
	return 0;
}

滑动窗口/单调队列

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+6;
typedef pair<int,int>PII;
int a[N],ansx[N],ansi[N],n,k;
priority_queue<PII>q;
priority_queue<PII,vector<PII>,greater<PII> >p;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>k;
    for(int i=1;i<=n;i++){
    	cin>>a[i];
    	q.push({a[i],i});
    	p.push({a[i],i});
    	if(i>=k){
    		while(q.size()&&i-q.top().second>=k)q.pop();
    		while(p.size()&&i-p.top().second>=k)p.pop();
    		ansx[i]=q.top().first;
    		ansi[i]=p.top().first;
		}
	}
	for(int i=k;i<=n;i++)cout<<ansi[i]<<" ";
	cout<<endl;
	for(int i=k;i<=n;i++)cout<<ansx[i]<<" ";
	return 0;
}

st表

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
const int N=1e6+6;
inline int read(){
	int s=0,w=1;
	char c=getchar();
	while(c<48||c>57){
		if(c=='-') w=-1;
		c=getchar();
	}
	while(c>=48&&c<=57)s=(s<<1)+(s<<3)+c-48,c=getchar();
	return s*w;
}
int n,m,f[N][50],s,e;
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		cin>>f[i][0];
	for(int j=1;j<=20;j++){
		for(int i=1;i<=n;i++){
			if(i+(1<<j)-1<=n)
				f[i][j]=min(f[i][j-1],f[i+(1<<j-1)][j-1]);
		}
	}
	for(int i=1;i<=m;i++){
		int l,r;
		cin>>l>>r;
		int o=log2(r-l+1);
		cout<<min(f[l][o],f[r-(1<<o)+1][o])<<" ";

	}
	return 0;
}

带权并查集

C++
#include<bits/stdc++.h>
using namespace std;
int fa[30001],front[30001],num[30001],x,y,i,j,n,T,ans;
char ins;
int find(int n){
    if(fa[n]==n)return fa[n];
    int fn=find(fa[n]);
    front[n]+=front[fa[n]];
    return fa[n]=fn;
}
int main(){
    cin>>T;
    for(i=1;i<=30000;++i){
        fa[i]=i;
        front[i]=0;
        num[i]=1;
    }
    while(T--){
        cin>>ins>>x>>y;
        int fx=find(x);
        int fy=find(y);
        if(ins=='M'){
            front[fx]+=num[fy];
            fa[fx]=fy;
            num[fy]+=num[fx];
            num[fx]=0;
        }
        if(ins=='C'){
            if(fx!=fy)cout<<"-1"<<endl;
else cout<<abs(front[x]-front[y])-1<<endl;
        }
    }
    return 0;
}

字典树

C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
#define mod 998244353
using namespace std;
const int N=3e6+6,inf=2e18;
typedef pair<int,int>PII;
int T,q,n,a[N][65],cnt[N],idx;
char s[N];
int getnum(char x){
	if(x>='A'&&x<='Z')
		return x-'A';
	else if(x>='a'&&x<='z')
		return x-'a'+26;
	else
		return x-'0'+52;
}
void insert(char str[]){
	int p=0,len=strlen(str);
	for(int i=0;i<len;i++){
		int c=getnum(str[i]);
		if(!a[p][c])
			a[p][c]=++idx;
		p=a[p][c];
		cnt[p]++;
	}
}
int find(char str[]){
	int p=0,len=strlen(str);
	for(int i=0;i<len;i++){
		int c=getnum(str[i]);
		if(!a[p][c])
			return 0;
		p=a[p][c];
	}
	return cnt[p];
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>T;
	while(T--){
		for(int i=0;i<=idx;i++)
			for(int j=0;j<=122;j++)
				a[i][j]=0;
		for(int i=0;i<=idx;i++)
			cnt[i]=0;
		idx=0;
		cin>>n>>q;
		for(int i=1;i<=n;i++){
			cin>>s;
			insert(s);
		}
		for(int i=1;i<=q;i++){
			cin>>s;
			cout<<find(s)<<endl;
		}
	}
	return 0;
}

线段树

C++
#include<bits/stdc++.h>
#define int long long

using namespace std;
const int N=1e6+6;
int a[N],t[N<<2],lz[N<<2];
void lazy(int ro,int l,int r,int k);
void push_down(int ro,int l,int r);
void push_up(int ro,int l,int r);
void built(int ro,int l,int r);
void update(int ro,int l,int r,int x,int y,int k);
int aks(int ro,int l,int r,int x,int y);
signed main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    int n,m;cin>>n>>m;
    for(int i=1;i<=n;++i)cin>>a[i];
    built(1,1,n);
    for(;m;m--) {
        int op;cin>>op;
        if(op==1) {
            int x,y,k;cin>>x>>y>>k;
            update(1,1,n,x,y,k);
        }
        else if(op==2) {
            int x,y;cin>>x>>y;
            cout<<aks(1,1,n,x,y)<<endl;
        }
    }
    return 0;
}
void lazy(int ro,int l,int r,int k) {
    t[ro]+=k*(r-l+1),lz[ro]+=k;
}
void push_down(int ro,int l,int r) {
    if(!lz[ro])return;
    int mid=l+r>>1;
    lazy(ro<<1,l,mid,lz[ro]),lazy(ro<<1|1,mid+1,r,lz[ro]);
    lz[ro]=0;
}
void push_up(int ro) {
    t[ro]=t[ro<<1]+t[ro<<1|1];
}
void built(int ro,int l,int r) {
    lz[ro]=0;
    if(l==r) {
        t[ro]=a[l];return;
    }
    int mid=l+r>>1;
    built(ro<<1,l,mid),built(ro<<1|1,mid+1,r);
    push_up(ro);
}
void update(int ro,int l,int r,int x,int y,int k) {
    if(x<=l&&r<=y) {
        lazy(ro,l,r,k);
        return;
    }
    push_down(ro,l,r);
    int mid=l+r>>1;
    if(x<=mid)update(ro<<1,l,mid,x,y,k);
    if(mid<y)update(ro<<1|1,mid+1,r,x,y,k);
    push_up(ro);
}
int aks(int ro,int l,int r,int x,int y){
    if(x<=l&&r<=y) {
        return t[ro];
    }
    push_down(ro,l,r);
    int res=0;
    int mid=l+r>>1;
    if(x<=mid)res+=aks(ro<<1,l,mid,x,y);
    if(mid<y)res+=aks(ro<<1|1,mid+1,r,x,y);
    return res;
}

01背包

C++
#include <cstdio>
#include <algorithm>
using namespace std;

long long W , N , dp[100005] , w[10005] , v[10005];

int main(void){
	scanf("%lld%lld" , &N , &W);
	for(int i = 1;i <= N;i++)
		scanf("%lld%lld" , &w[i] , &v[i]);
	for(int i = 1;i <= N;i++)
		for(int j = W;j >= 0;j--)
			if(j - w[i] >= 0)
				dp[j] = max(dp[j - w[i]] + v[i] , dp[j]);
	printf("%lld\n" , dp[W]);
}

完全背包

C++
#include <cstdio>
#include <iostream>
#define maxn 500005
using namespace std;

int dp[maxn];
int N , W;
int w[505] , v[505];

int main(void){
	scanf("%d%d" , &N , &W);
	for(int i = 1;i <= N;i++)
		scanf("%d%d" , &w[i] , &v[i]);
	for(int i = 1;i <= N;i++)
		for(int j = w[i];j <= W;j++)
			dp[j] = max(dp[j] , dp[j - w[i]] + v[i]);
	printf("%d\n" , dp[W]);
}

多重背包

C++
#include <cstdio>
#include <iostream>
using namespace std;

int dp[505][50005];
int N , W;
int w[505] , v[505];

int main(void){
	scanf("%d%d" , &N , &W);
	for(int i = 1;i <= N;i++)
		scanf("%d%d" , &w[i] , &v[i]);
	for(int i = 1;i <= N;i++){
		for(int j = 1;j <= W;j++){
			for(int k = 0;k <= min(2 , j / w[i]);k++){
				dp[i][j] = max(dp[i][j] , dp[i - 1][j - w[i] * k] + v[i] * k);
			}
		}
	}
	printf("%d\n" , dp[N][W]);
}

差分

C++
#include <iostream>
using namespace std;

int n , m , last;
int sum[10005] , b[10005] , s[10005];

int main(void){
	cin.tie(0);
	cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n;i++){
    	int x;
        cin >> x;
        b[i] = x - last;
        last = x;
    }
    cin >> m;
    for(int i = 1;i<=m;i++){
    	int l , r , x;
        cin >> l >> r >> x;
        b[l] += x;
		b[r + 1] -= x;
    }
    for(int i = 1;i <= n;i++){
        s[i] = s[i - 1] + b[i];
        sum[i] = sum[i - 1] + s[i];
    }
	cin >> l >> r;
	cout << sum[r] - sum[l - 1] << "\n";
}

GCD

C++
inline long long gcd(long long x , long long y){
  	return (y > 0? gcd(y , x % y) : x);
}

LCM

C++
inline long long lcm(long long x , long long y){
  	return x / gcd(x , y) * y;
}

LCA最近公共祖先

C++
int N , M , S;
vector <int> g[500005];
int shen[500005];
int fa[500005][22] , lg[500005];
bool vis[500005];

void dfs(int x , int y , int father){
	if(vis[x])
		return ;
	vis[x] = true;
	shen[x] = y;
	fa[x][0] = father;
	for(int i = 1;i <= lg[shen[x]];i++)
		fa[x][i] = fa[fa[x][i - 1]][i - 1];
		//2^i = 2^(i - 1) + 2^(i - 1)
	for(int next : g[x])
		dfs(next , y + 1 , x);
}

int LCM(int x , int y){
	if(shen[x] < shen[y])
		swap(x , y);
	while(shen[x] > shen[y])
		x = fa[x][lg[shen[x] - shen[y]] - 1];
	if(x == y)
		return x;
	for(int k = lg[shen[y]] - 1;k >= 0;k--){
		if(fa[x][k] != fa[y][k]){
			x = fa[x][k];
			y = fa[y][k];
		}
	}
	return fa[x][0];
}

int main(void){
	scanf("%d%d%d" , &N , &M , &S);
	for(int i = 1;i < N;i++){
		int a , b;
		scanf("%d%d" , &a , &b);
		g[a].push_back(b);
		g[b].push_back(a);
	}
	for(int i = 1;i <= N;i++)
		lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
	dfs(S , 1 , 0);
	while(M--){
		int a , b;
		scanf("%d%d" , &a , &b);
		printf("%d\n" , LCM(a , b));
	}
}

二分图最大权完美匹配

C++
#include <cstdio>
#include <vector>
#include <cstring>
#define inf 0x7fffffffffffffff
using namespace std;

int n , m , e;
vector <int> g[505];
// vector <long long> gv[505];
bool visl[505] , visr[505];
long long www[505][505];
long long lj[505] , aaa[505] , bbb[505]; //a,b好感
long long qwq , ans; //要降的期待值

char buf[1 << 21] , *p1 , *p2;
#define GC p1 == p2 && (p2 = (p1 = buf) + fread(buf , 1 , 1 << 21 , stdin) , p1 == p2) ? EOF : *p1++
inline int read() {
	int x = 0;
    bool f = false;
	char ch = GC;
	while(ch > '9' || ch < '0'){
        if(ch == '-')
            f = true;
        ch = GC;
    }
	while(ch >= '0' && ch <= '9'){
		x = (x << 1) + (x << 3) + (ch ^ 48);
		ch = GC;
	}
	return f? -x : x;
}

bool dfs(int x){
    visl[x] = true;
    int len = g[x].size();
    for(int i = 0;i < len;i++){
        int next = g[x][i];
        if(visr[next])
            continue;
        if(aaa[x] + bbb[next] == www[x][next]){
            visr[next] = true;
            if(!lj[next] || dfs(lj[next])){
                lj[next] = x;
                visr[next] = true;
                return true;
            }
        }
        else
            qwq = min(qwq , aaa[x] + bbb[next] - www[x][next]);
    }
    return false;
}

void find(){
    for(int i = 1;i <= n;i++){
        aaa[i] = -inf;
        for(int next : g[i])
            aaa[i] = max(www[i][next] , aaa[i]);
    }
    for(int i = 1;i <= n;i++){
        while(true){
            memset(visl , 0 , sizeof(visl));
            memset(visr , 0 , sizeof(visr));
            qwq = inf;
            if(dfs(i))
                break;
            for(int j = 1;j <= n;j++)
                if(visl[j])
                    aaa[j] -= qwq;
            for(int j = 1;j <= m;j++)
                if(visr[j])
                    bbb[j] += qwq;
        }
    }
}

int main(void){
    n = read() , e = read();
    m = n;
    while(e--){
        int u , v;
        long long w;
        u = read() , v = read() , w = read();
        g[u].push_back(v);
        www[u][v] = w;
    }
    find();
    for(int i = 1;i <= n;i++)
        ans += www[lj[i]][i];
    printf("%lld\n" , ans);
    for(int i = 1;i <= n;i++)
        printf("%d " , lj[i]);
}

小技巧篇

位运算加法

C++
#include<bits/stdc++.h>
using namespace std;
int add(int a,int b){
	return ((a&b)?add(a^b,(a&b)<<1):a^b);
}
signed main(){
	int a,b;
	cin>>a>>b;
	cout<<add(a,b)<<endl;
	//等价于:cout<<a+b<<endl;
	return 0;
}

二分查找(数组容量1005,找到的是最后一个合法位置)

C++
#include<bits/stdc++.h>
using namespace std;
signed main(){
	int arr[1005];
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) cin>>arr[i];
	int l=1,r=n;
	int target;
	cin>>target;
	while(l<=r){
		int mid=l+r>>1;
		if(arr[mid]<target){
			l=mid+1;
		}else if(arr[mid]>target){
			r=mid-1;
		}else{
			cout<<mid<<endl;
			return 0;
		}
	}
	cout<<-1;
	return 0;
}

高精度篇(默认最大10510^5位)

高精度加法

C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
	string a,b;
	cin>>a>>b;
	int lena=a.length();
	int lenb=b.length();
	if(a=="0"&&b=="0"){
		cout<<0<<endl;
		return 0;
	}
	int a1[100000]={},b1[100000]={},c1[100000]={};
	for(int i=0;i<lena;i++){
		a1[lena-1-i]=a[i]-'0';
	}
	for(int i=0;i<lenb;i++){
		b1[lenb-1-i]=b[i]-'0';
	}
	int lenc=max(lena,lenb);
	int i=0;
	for(;i<=lenc;i++){
		c1[i]+=(a1[i]+b1[i]);
		c1[i+1]=c1[i]/10;
		c1[i]%=10;
	}
	for(;c1[i]==0;i--);
	for(;i>=0;i--){
		cout<<c1[i];
	}
	return 0;
}

高精度减

C++
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
const int N = 2e5 + 10;
using namespace std;
typedef pair<int, int> PII;
int a[100000]={0},b[100000]={0},res[100000]={0};
void solve() {
	string s1,s2;
	cin>>s1>>s2;
	int fl=1;
	if(s1==s2){
		cout<<0<<endl;
		return ;
	}
	if(s1.size()<s2.size()){
		fl=0;
		swap(s1,s2);
	}
	if(s1.size()==s2.size()&&s1<s2){
		fl=0;
		swap(s1,s2);
	}
	int l1=s1.length();
	int l2=s2.length();
	for(int i=0;i<l1;i++){
		a[l1-i-1]=s1[i]-'0';
	}
	for(int i=0;i<l2;i++){
		b[l2-i-1]=s2[i]-'0';
	}
	int i=0;
	for(;i<l1;i++){
		res[i]+=a[i]-b[i];
		if(res[i]<0){
			res[i+1]--;
			res[i]+=10;
		}
	}
	for(;res[i]==0;i--);
	string u="";
	if(fl==0)cout<<'-';
	for(;i>=0;i--)
		cout<<res[i];
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int _ = 1;
//  cin >> _;
	while (_--) solve();
	return 0;
}

高精度乘

C++
#include<bits/stdc++.h>
#include<cstdio>
#define endl '\n'
#define ll long long
#define isON(x) (x&1)
#define lbt(x) ((x) & (-(x)))
#define Rup(a,b) ((a+b-1)/b)
#define all(x) x.begin(),x.end()
#define gets(S) fgets(S,sizeof(S),stdin)
#define S(a,n,x) sort(a+x,a+x+n)
#define mod 998244353
#define int long long
//#define Fre
#define Ct

const int N = 2e5 + 10;

using namespace std;

typedef pair<int, int> PII;

int a1[100000]={},b1[100000]={},c1[100000]={};

void solve() {
	string a,b;
	cin>>a>>b;
	int lena=a.length();
	int lenb=b.length();
	if(a=="0"||b=="0"){
		cout<<0<<endl;
		return ;
	}
	for(int i=0;i<lena;i++){
		a1[lena-1-i]=a[i]-'0';
	}
	for(int i=0;i<lenb;i++){
		b1[lenb-1-i]=b[i]-'0';
	}
	for(int i=0;i<lena;i++){
		for(int j=0;j<lenb;j++){
			c1[i+j]+=a1[i]*b1[j];
			c1[i+j+1]+=c1[i+j]/10;
			c1[i+j]%=10;
		}
	}
	int i=lena+lenb;
	for(;c1[i]==0;i--);
	for(;i>=0;i--){
		cout<<c1[i];
	}
}

signed main() {

#ifdef Fre
	freopen("expert.in", "r", stdin);
	freopen("expert.out", "w", stdout);
#endif

#ifdef Ct
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
#endif

	int _ = 1;
//  cin >> _;
	while (_--) solve();

	return 0;
}

高精度除(整除,此代码先输出商后输出余数)

C++
#include<bits/stdc++.h>
#include<cstdio>
#define endl '\n'
#define ll long long
#define isON(x) (x&1)
#define lbt(x) ((x) & (-(x)))
#define Rup(a,b) ((a+b-1)/b)
#define all(x) x.begin(),x.end()
#define gets(S) fgets(S,sizeof(S),stdin)
#define S(a,n,x) sort(a+x,a+x+n)
#define mod 998244353
#define int long long
//#define Fre
#define Ct

const int N = 2e5 + 10;

using namespace std;

typedef pair<int, int> PII;

int a[N] = {0}, b[N] = {0}, c[N] = {0}, tmp[N] = {0}, len_a, len_b, len_c, len_t;
string s1, s2;
void mymove(int distance) {
	for (int i = 1; i <= len_b; i++) {
		tmp[i + distance - 1] = b[i];
	}
	len_t = len_b + distance - 1;
}
bool cmp() {
	if (len_a > len_t) return true;
	if (len_a < len_t) return false;
	for (int i = len_a; i >= 1; i--) {
		if (a[i] > tmp[i]) return true;
		if (a[i] < tmp[i]) return false;
	}
	return true;
}
void subtraction() {
	for (int i = 1; i <= len_t; i++) {
		a[i] -= tmp[i];
		if (a[i] < 0)
			a[i + 1]--, a[i] += 10;
	}
	while (a[len_a] == 0 && len_a > 1) len_a--;
}

void solve() {
	cin >> s1 >> s2;
	if(s1=="0"){
		cout<<0<<endl<<0;
		return ;
	}
	len_a = s1.length(), len_b = s2.length();
	for (int i = 0; i < len_a; i++) a[len_a - i] = s1[i] - '0';
	for (int i = 0; i < len_b; i++) b[len_b - i] = s2[i] - '0';
	len_c = len_a - len_b + 1;
	for (int i = len_c; i >= 1; i--) {
		mymove(i);
		while (cmp()) {
			c[i]++;
			subtraction();
		}
	}
	while (c[len_c] == 0 && len_c > 1) len_c--;
	for (int i = len_c; i >= 1; i--) {
		cout << c[i];
	}
	cout << endl;
	for (int i = len_a; i >= 1; i--) {
		cout << a[i];
	}
}

signed main() {

#ifdef Fre
	freopen("expert.in", "r", stdin);
	freopen("expert.out", "w", stdout);
#endif

#ifdef Ct
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
#endif

	int _ = 1;
//  cin >> _;
	while (_--) solve();

	return 0;
}

——THE END——

致谢致谢

真菌团队\small真菌团队

主编:灵感菇。\tiny 主编:灵感菇。 链接:金针菇,鸡油菌,鸡枞菌,青头菌。\tiny 链接:金针菇,鸡油菌,鸡枞菌,青头菌。 图片:奶浆菌,平菇,香菇,口蘑。\tiny 图片:奶浆菌,平菇,香菇,口蘑。 Markdown:毒蝇伞,珊瑚菌,出血齿菌,见手青。\tiny Markdown:毒蝇伞,珊瑚菌,出血齿菌,见手青。 Katex:杏鲍菇,酵母菌,玉米瘤黑粉菌。\tiny Katex:杏鲍菇,酵母菌,玉米瘤黑粉菌。

一篇好的代码wiki需要尾图:

原文