本文主要是介绍二分法三分法 - 模板,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
快速幂模板:
int fun(int x, int n) //x^n
{int pw = 1;while (n > 0) {if ((n % 2) == 1) // n & 1 等价于 (n % 2) == 1pw *= x;x *= x;n /= 2; // n >>= 1 等价于 n /= 2}return pw;
}
二分查找法模板:
/* 在数组b中查找是否有数组a中的元素 */
#include <stdio.h>
#include <stdlib.h>
int comp(const void *a, const void *b)
{return *(int *)a - *(int *)b;
}
int main()
{int n, m;int i, j, x, y, s, mid;int a[100010], b[100010];while (scanf("%d%d", &n, &m) != EOF){for (i = 0; i < n; i++)scanf("%d", &a[i]);for (i = 0; i < m; i++)scanf("%d", &b[i]);qsort(a, n, sizeof(int), comp);for (i = 0; i < m; i++){x = n - 1;y = 0;s = 1;while (x >= y){mid = (x + y) / 2;if (b[i] == a[mid]){printf("yes\n");s = 0;break;}elseif (b[i] < a[mid])x = mid - 1;elsey = mid + 1;}if (s == 1)printf("no\n");}}return 0;
}
三分查找法模板:(转)
bool three_divide_search(int *a, int n, int val)// 数组a,长度n, a[0]-a[n-1],查找val,若存在返回true
{ //数组已从小到大排好序if (val<a[0] || val>a[n - 1]) return false;int ll = 0, rr = n - 1;int mid1, mid2;while (ll <= rr){int len = rr - ll + 1;if (len == 1) return a[ll] == val;else if (len == 2) return (a[ll] == val) || (a[rr] == val);mid1 = len / 3 + ll;mid2 = len / 3 * 2 + ll;if (a[mid1] == val) return true;else if (a[mid1] > val) rr = mid1 - 1;else //在mid1+1,rr中找{if (a[mid2] == val) return true;else if (a[mid2] > val) { ll = mid1 + 1; rr = mid2 - 1; }else ll = mid2 + 1;}}return false;
}
这篇关于二分法三分法 - 模板的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!