数论
GCD
int gcd(int a, int b){
if(b == 0) return a;
return gcd(b, a % b);
}
快速幂
int quick_pow(int a, int b, int p){
int ans = 1;
while(b){
if(b % 2)
ans = (ans * a) % p;
a *= a;
a %= p;
b /= 2;
}
return ans;
}
EXGCD
int a, b, x, y;
int exgcd(int a, int b, int &x, int &y){
if(b == 0){
x = 1, y = 0;
return a;
}
int xx = 0, yy = 0;
int d = exgcd(b, a % b, xx, yy);
x = yy;
y = xx - a / b * yy;
return d;
}
排序
插入排序
int a[105], n;
void insert_sort(){
for(int i = 1; i < n; i++)
for(int j = i; j > 0; j--)
if(a[j] < a[j - 1])
swap(a[j], a[j - 1]);
}
选择排序
int a[105], n;
void select_sort(){
for(int i = 0; i < n - 1; i++){
int idx = i;
for(int j = i + 1; j < n; j++)
if(a[idx] > a[j]) idx = j;
swap(a[i], a[idx]);
}
}
归并排序
int a[105], n;
int tmp[105];
void merge_sort(int l, int r){
if(l >= r) return;
int mid = l + r >> 1;
merge_sort(l, mid);
merge_sort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r){
if(arr[i] < arr[j]) tmp[k++] = a[i++];
else tmp[k++] = a[j++];
}
while(i <= mid) tmp[k++] = a[i++];
while(j <= r) tmp[k++] = a[j++];
for(i = 0, j = l; j <= r; i++, j++) a[j] = tmp[i];
}
快速排序
int a[105], n;
void quick_sort(int l, int r){
if(l >= r) return;
int i = l - 1, j = r + 1, x = a[l + r >> 1];
while(i < j){
do{
i++;
}while(a[i] < x);
do{
j--;
}while(a[j] > x);
if(i < j) swap(a[i], a[j]);
}
quick_sort(l, j);
quick_sort(j + 1, r);
}
高级数据结构
map(映射)
map<string, int> m;
m["abc"] = 233;
cout << m.size() << endl;
for(auto it : m) cout << it.frist << " " << it.second << endl;
m.clear()
queue(队列)
queue<int> q;
q.push(233);
q.pop();
cout << q.front() << endl;
cout << q.size() << endl;
deque(双端队列)
deque<int> d;
d.push_back(233);
d.push_front(233);
d.pop_back();
d.pop_front();
cout << q.size() << endl;
cout << q.front() << endl;
cout << q.back() << endl;
priority_queue(堆)
大根堆
priority_queue<int> p;
p.push(233);
p.pop();
cout << p.top() << endl;
cout << p.size() << endl;
小根堆
priority_queue<int, vector<int>, greater<int> > p;
p.push(233);
p.pop();
cout << p.top() << endl;
cout << p.size() << endl;
set(集合)
set<int> s
st.insert(233);
cout << s.size() << endl;
cout << s.count(233) << endl;
s.erase(233);
for(auto it : s) cout << it << endl;
s.clear()
pair(二元组 )
pair<int, int> p;
p.first = 233;
p.second = 233;
vector(动态数组)
vector<int> v;
v.push_back(233);
v.pop_back();
cout << z.size() << endl;
v.resize(1000);
动态规划
背包
01背包
cin >> n >> m;
for(int i = 1; i <= n; i++){
cin >> v >> w;
for(int j = 1; j <= v; j++)
dp[j] = max(dp[j], dp[j - v] + w);
}
cout << dp[m];
完全背包
cin >> n >> m;
for(int i = 1; i <= n; i++){
cin >> v >> w;
for(int j = v; j <= m; j++)
dp[j] = max(dp[j], dp[j - v] + w);
}
cout << dp[m];
多重背包
cin >> n/*物品数量*/ >> m/*背包容量*/;
for(int i = 1; i <= n; i++){
cin >> v/*物品体积*/ >> w/*物品价值*/ >> s/*物品数量*/;
for(int j = T; j >= v; j--)
for(int k = 0; k <= s && k * v <= j; k++)
dp[j] = max(dp[j], dp[j - k * v] + k * w);
}
cout << dp[V];
注:以后还会陆续更新!!!