算法模板总结
Posted shuitiangong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法模板总结相关的知识,希望对你有一定的参考价值。
排序:
1.冒泡排序(什么?你也是冒泡人?):
void bubble_Sort(int* arr, int n) { for (int i = 0; i<n-1; ++i) for (int j = 0; j<n-i-1; ++j) if (arr[j] > arr[j+1]) swap(arr[j], arr[j+1]); }
2.快速排序:
void quickSort(int* arr, int low, int high) { if (low >= high) return; int kase = low; for (int i = low; i<high; i++) if (arr[i] < arr[high]) swap(arr[kase++], arr[i]); swap(arr[kase], arr[high]); quickSort(arr, low, kase-1); quickSort(arr, kase+1, high); }
3.归并排序:
void mergeSort(int arr[], int temp[], int low, int high) { if (low >= high) return; int len = high-low, mid = len/2 + low; int start1 = low, end1 = mid, start2 = mid+1, end2 = high; mergeSort(arr, temp, start1, end1); mergeSort(arr, temp, start2, end2); int index = low; while(start1 <= end1 && start2 <= end2) temp[index++] = arr[start1] <= arr[start2] ? arr[start1++] : arr[start2++]; while(start1 <= end1) temp[index++] = arr[start1++]; while(start2 <= end2) temp[index++] = arr[start2++]; for (int i = low; i<=high; i++) arr[i] = temp[i]; }
4.待续....
快速幂&&快速乘:
1.快速幂:
ll quickPow(ll x, ll y) { if (!y) return 1; ll res = quickPow(x, y >> 1); res = res*res%MOD; if (y&1) res = res*x%MOD; return res; }
2.快速乘:
ll solve(ll n, ll m) { if (!n || !m) return 0; ll res = solve(n, m>>1); res = res<<1 % MOD; if (m&1) res = (res+n) % MOD; return res; }
高精度:
1.加法
void sum() { int len1 = strlen(num1); int len2 = strlen(num2); reverse(num1, num1+len1); reverse(num2, num2+len2); int kase = 0; while(kase < len1 && kase < len2) { res[kase+1] = (res[kase] + num1[kase] + num2[kase] - ‘0‘*2)/10; res[kase] = (res[kase] + (num1[kase] + num2[kase] - ‘0‘*2))%10 + ‘0‘; ++kase; } while(kase < len1) { res[kase+1] = (res[kase] + num1[kase] - ‘0‘)/10; res[kase] = (res[kase] + num1[kase] - ‘0‘)%10 + ‘0‘; ++kase; } while(kase < len2) { res[kase+1] = (res[kase] + num2[kase] - ‘0‘)/10; res[kase] = (res[kase] + num2[kase] - ‘0‘)%10 + ‘0‘; ++kase; } res[kase] += ‘0‘; for (int i = kase; i>=0; i--) { if (res[kase] == ‘0‘) continue; cout << res[i]; } cout << endl; fill(num1, num1+maxn, 0); fill(num2, num2+maxn, 0); fill(res, res+maxn, 0); }
尺取法:
以上是关于算法模板总结的主要内容,如果未能解决你的问题,请参考以下文章