摘要:List some tips when using C/C++.Use std::sort instead of qsort (At least, in Visual C++). This is because std::sort is faster than qsort. Keys in an associative container are immutable. Keep it in mind, expecially when you are using std::set and std::multiset. Also, iterator and const_iterator for s
阅读全文
摘要:1. 判断一个自然数是否是2n形式(n >= 0)bool IsPowerOfTwo(int x){ return ((x & (x - 1)) == 0 ) && (x != 0);} 2. 求两个整数的平均值单纯的(x+y)/2可能存在x+y溢出的风险。int Average(int x, int y){ return (x & y) + ((x ^ y) >> 1);} 3. 计算整数绝对值template <typename T>T Abs(T x){ T y = x >> ((sizeof(T) <<
阅读全文
摘要:字符串的编辑距离也被称为Levenshtein距离(Levenshtein Distance),一般用动态规划来实现。属于经典算法。这里对编辑距离进行简单的分析(经典算法,所以记录一下:-))。我们假定函数dist(str1, str2)表示字串str1转变到字串str2的编辑距离,那么对于下面3种极端情况,我们很容易给出解答(0表示空串)。dist(0, 0) = 0dist(0, s) = strlen(s)dist(s, 0) = strlen(s)对于一般的情况,dist(str1, str2)我们应该如何求解呢?假定我们现在正在求解dist(str1+char1, str2+char
阅读全文
摘要:先给出Fibonacci的定义:简单地总结了下,至少有5中方法来求Fibonacci(n)。直接带公式简单递归循环改进的递归使用矩阵这里主要介绍下如何用矩阵来求F(n)。直接公式简单递归int Fibonacci(int n){ if (1 >= n) return n; else return Fibonacci(n – 1) + Fibonacci(n – 2);} 循环int Fibonacci(int n){ int fib_n1 = 0, fib_n2 = 1; int fib_n; if (n <= 1) return n; for (int i...
阅读全文
摘要:求幂的O(logn)算法应该已经众所周知了。这里就不做深入地分析,只是简单介绍下并提供两个样板程序。在写下O(logn)算法之前,还是先补充介绍下算法的数学背景。显然,上面的数学式具有递归形式。所以,递归实现可以写成:int Power(int base, unsigned exponent){ if (0 == exponent) return 1; if (1 == exponent) return base; if (exponent & 1) return Power(base * base, exponent >> 1) * base; else...
阅读全文