为什么每次写KMP都这么艰难?


#include <iostream>
#include <vector>
using namespace std;

vector<int> Target(char* subString)
{
vector<int> next;
if(NULL == subString)
return next;
int len = strlen(subString);
next.resize(len + 1);
next[0] = -1;
for(int i = 0; i < len; ++i)
{
next[i + 1] = next[i] + 1;
while(next[i + 1] > 0 && subString[i] != subString[next[i + 1] - 1])
next[i + 1] = next[next[i + 1] - 1] + 1;
}
return next;
}
int KMP(char* oriString, char* subString)
{
int i = 0;
int j = 0;
int s_len = strlen(oriString);
int p_len = strlen(subString);
vector<int> next = Target(subString);
while(i < s_len && j < p_len)
{
if(j == -1 || oriString[i] == subString[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if(j == p_len)
return i - p_len;
return -1;
}
int main()
{
int index = KMP("xyzabcabcabcabcdef", "abcabcd");
return 0;
}

Posted in Computer Science & Engineer | Leave a comment

Dynamic Programming Practice Problems

Click This Link

Posted in Computer Science & Engineer | Leave a comment

Semaphores

Semaphores are used when you want several thread to access the same variables safely. Imagine the situation that you have an input buffer you want to read out continuously with one thread, while another thread fills it with new input from e.g. the serial port or somthing else.

While the read-thread is reading out the buffer, there might already be new incoming input at the serial port. Without semaphores you’d maybe lose some of the incoming data or witness any other strange behavior of your program.

So a semaphore is something like a “traffic light” if you want to make it really simple. Before a thread can access the “dangerous” variables/functions it has to obtain the semaphore first. Once it has obtained the semaphore it switches the semaphore status to “OK guys, it’s my turn now!”. Now the “traffic light” is red and another thread will have to wait until the first thread releases the semaphore again to signal that it is done with whatever it wanted to do.

When the first thread release the semaphore, it switches the semepahore’s status back to “Freedom”, now the other thread has the chance to obtain the semaphore and perform some actions…

In Windows, you might want to check the:
CreateSemaphore();
WaitForSingleObject();
ReleaseSemphore();

function. They are used to create, obtain and release a semaphore under windows. It’s a little bit different in Linux, but the idea is basically the same.

The following example uses a semaphore object to limit the number of threads that can perform a particular task. First, it uses the CreateSemaphore function to create the semaphore and to specify initial and maximum counts, then it uses the CreateThread function to create the threads.

Before a thread attempts to perform the task, it uses the WaitForSingleObject function to determine whether the semaphore’s current count permits it to do so. The wait function’s time-out parameter is set to zero, so the function returns immediately if the semaphore is in the nonsignaled state. WaitForSingleObject decrements the semaphore’s count by one.

When a thread completes the task, it uses the ReleaseSemaphore function to increment the semaphore’s count, thus enabling another waiting thread to perform the task.


#include
#include

#define MAX_SEM_COUNT 10
#define THREADCOUNT 12

HANDLE ghSemaphore;
DWORD WINAPI ThreadProc(LPVOID);

int main()
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
// Crate a semaphore with initial and max counts of MAX_SEM_COUNT
ghSemaphore = ::CreateSemaphore(NULL, // Default security attributes
MAX_SEM_COUNT, // Initial count
MAX_SEM_COUNT, // Maximum count
NULL);
if(NULL == ghSemaphore)
{
printf("CreateSamaphore error: %d\n", GetLastError());
return 1;
}

// Create worker threads;
for(i = 0; i < THREADCOUNT; ++i)
{
aThread[i] = CreateThread(NULL, // Default security attributes
0, // Default stack size,
(LPTHREAD_START_ROUTINE)ThreadProc,
NULL,
0,
&ThreadID);
if(NULL == aThread[i])
{
printf("CreateThread error: %d\n", GetLastError());
return 1;
}
}

// Wait for all thread to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);

// Close thread and samaphore handles
for(i = 0; i < THREADCOUNT; ++i)
{
CloseHandle(aThread[i]);
}
CloseHandle(ghSemaphore);
return 0;
}

DWORD WINAPI ThreadProc(LPVOID lpParam)
{
// lpParam not used in this example, without this Macro, Source depot complains.
UNREFERENCED_PARAMETER(lpParam);
DWORD dwWaitResult;
BOOL bContinue = TRUE;
while(bContinue)
{
// Try to enter the semaphore gate;
dwWaitResult = WaitForSingleObject(ghSemaphore, 0L);
switch(dwWaitResult)
{
// The semaphore object was signaled.
case WAIT_OBJECT_0:
printf("Thread %d: wait succeeded\n", GetCurrentThreadId());
bContinue = FALSE;
// simulate thread spending time on task
Sleep(5);

// Release the semaphore when task is finished
if(!ReleaseSemaphore(ghSemaphore, 1, NULL))
{
printf("ReleaseSemaphore error: %\n", GetLastError());
}
break;
case WAIT_TIMEOUT:
printf("Thread %d: wait time out\n", GetCurrentThreadId());
break;
}
}
return TRUE;
}

Here is the result on my machine
Thread 5752: wait succeeded
Thread 1284: wait succeeded
Thread 5812: wait succeeded
Thread 5864: wait succeeded
Thread 5144: wait succeeded
Thread 4736: wait succeeded
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait time out
Thread 3428: wait succeeded
Thread 2816: wait succeeded
Thread 6012: wait succeeded
Thread 5436: wait succeeded
Thread 3372: wait succeeded
Thread 1076: wait time out
Thread 1076: wait succeeded
Press any key to continue . . .

Posted in Computer Science & Engineer | Leave a comment

Largest rectangle in histogram problem

Largest rectangle in histogram problem

Problem Descriptor

Solution

Posted in Computer Science & Engineer | Leave a comment

一道题

数组A[1,n]
找出 index a,b 使得 A[a]+A[a+1]+…+A[b] = 0;


HashTable ht;
int a = -1, b = -1;
int sum = 0;
int i;
ht.add(sum, 0);
for (i = 1;i <=n; i++) {
sum += A[i];
if (ht.has(sum)) {
a = ht.get(sum) + 1;
b = i;
break;
}
ht.add(sum, i);
}

Posted in Computer Science & Engineer | Leave a comment

perfect number完美数

一个数如果恰好等于它的因子之和,这个数就称为”完美数”或”完数”。例如6=1+2+3.(6的因子是1,2,3) 完美数的一些性质:
欧几里德证明了:一个偶数是完数,当且仅当它具有如下形式:2(p-1)×(2p-1) 其中p和(2p-1)是素数。 尽管没有发现奇完数,但是当代数学家奥斯丁·欧尔(Oystein Ore)证明,若有奇完全数,则其形状必然是12p+1或36p+9的形式,其中p是素数。在1018以下的自然数中奇完数是不存在的。
除6以外的偶完数,把它的各位数字相加,直到变成一位数,那么这个一位数一定是1(亦即:除6以外的完数,被9除都余1) 28:2+8=10,1+0=1 496:4+9+6=19,1+9=10,1+0=1
因为 2p 是 2的幂,用C语言也就是1 << p,那么 2p-1 的二进制也就是p个1组成了,而 2(p-1) 是 2的幂,这两个数相乘,也就相当于把 2p-1 向左移 p-1 位,即 (2p-1) << (p-1),那所有完美数的二进制就是前面p个1,后面跟着p-1个0。 所以偶完数都可以表达为2的一些连续正整数次幂之和,如: 6=2(1 ) + 2(2 ) 28=2(2 ) + 2(3) + 2(4) 8128=2(6) + 2(7) + ... + 2(12) 33550336=2(12) + 2(13 ) + ... + 2(24)
j = ((1 + (i ^ (i-1) )) >> 1) + i – 1; (j & (j + 1)) || (i & 1)
上面的代码可以判断整数i是否是前面1后面0的形式。
每一个偶完数都可以写成连续自然数之和: 6=1+2+3 28=1+2+3+4+5+6+7 496=1+2+3+…+30+31
除6以外的偶完数,还可以表示成连续奇数的立方和(被加的项共有): 28 = 1(3) + 3(3) 496 = 1(3) + 3(3) + 5(3) + 7(3) 8128 = 1(3) + 3(3) + 5(3) + … + 15(3) 33550336 = 1(3) + 3(3) + 5(3) + … + 125(3) + 127(3)
每一个完数的所有约数(包括本身)的倒数之和,都等于2: 1/1 + 1/2 + 1/3 + 1/6 = 2 1/1 + 1/2 + 1/4 + 1/7 + 1/14 + 1/28 = 2
了解了上面一些性质后,就可以简单的来写一个求完美数的程序了。
#include #ifndef WIN32 typedef long long ll; #else typedef __int64 ll; #endif int main(void) { ll i, j, n, x; for (n = 2; n <= 31; n++) { x = (1 << n) – 1; for(i = 3; i*i <= x; i += 2) if(x % i == 0) break; if(i*i <= x) continue; printf(“%lld/n”, (1 << (n – 1)) * x); } return 0; }
运行结果:
6 28 496 8128 33550336 8589869056 137438691328 2305843008139952128
到目前为止,已经求出的2p-1是素数的有25个:2、3、5、7、13、17、19、31、61、89、107、127、521、607、1279、2203、2281、3217、4253、4423、9689、9941、11213、19937、21701。 据说最后一个即221701-1是1978年两名美国大学生新发现的截止目前为止最大的一个素数 所有我们可以利用这个结果来求已知的完美数:

Posted in Computer Science & Engineer | Leave a comment

C++ 对象生死

下面的代码会调用A的析构函数。此处A为一个对象。

#include "iostream"
using namespace std;

class A
{
public:
A()
{
cout << "Constructor of A" << endl;
}
virtual ~A()
{
cout << "DeConstructor of A" << endl;
}
};

class B
{
public:
B()
{
A a;
std::exception e("Test exception");
throw e;
}
virtual ~B()
{

}
};
int main()
{
try
{
B b;
}catch(std::exception& e)
{
}
return 0;
}

下面的代码不会调用A的析构函数。此处A为一个指针。B没有生成,所以没有调用B的析构,也就没调用A的析构。其他语言可能有不同行为。

#include “iostream”
using namespace std;

class A
{
public:
A()
{
cout << "Constructor of A" << endl;
}
virtual ~A()
{
cout << "DeConstructor of A" << endl;
}
};

class B
{
public:
B()
{
_pA = new A();
std::exception e("Test exception");
throw e;
}
virtual ~B()
{
if(NULL != _pA)
{
delete _pA;
_pA = NULL;
}
}
private:
A* _pA;
};
int main()
{
try
{
B b;
}catch(std::exception& e)
{
}
return 0;
}

Posted in Computer Science & Engineer | Leave a comment

Rand7 from Rand5


#include "iostream"
#include "ctime"
using namespace std;

class Random
{
public:
Random()
{
srand(time(0));
}
const int rand5()
{
return rand() % 5;
}
private:
};
class Rand7
{
public:
const int rand7()
{
while(true)
{
int t1 = random.rand5() * 5;
int t2 = random.rand5();
int s = t1 + t2;
if(s < 21)
return s % 7;
}
}
private:
Random random;
};

int main()
{
int appearTimes[7] = {0};
Rand7 rand7;
for(int i = 0; i < 10000000; ++i)
{
int t = rand7.rand7();
appearTimes[t]++;
}
for(int i = 0; i < 7; ++i)
{
cout << i << ": " << appearTimes[i] << endl;
}
return 0;
}

Posted in Computer Science & Engineer | Leave a comment

学习算法之路

第一阶段:练经典常用算法,下面的每个算法给我打上十到二十遍,同时自己精简代码,
因为太常用,所以要练到写时不用想,10-15分钟内打完,甚至关掉显示器都可以把程序打
出来.
1.最短路(Floyd、Dijstra,BellmanFord)
2.最小生成树(先写个prim,kruscal要用并查集,不好写)
3.大数(高精度)加减乘除
4.二分查找. (代码可在五行以内)
5.叉乘、判线段相交、然后写个凸包.
6.BFS、DFS,同时熟练hash表(要熟,要灵活,代码要简)
7.数学上的有:辗转相除(两行内),线段交点、多角形面积公式.
8. 调用系统的qsort, 技巧很多,慢慢掌握.
9. 任意进制间的转换

第二阶段:练习复杂一点,但也较常用的算法。
如:
1. 二分图匹配(匈牙利),最小路径覆盖
2. 网络流,最小费用流。
3. 线段树.
4. 并查集。
5. 熟悉动态规划的各个典型:LCS、最长递增子串、三角剖分、记忆化dp
6.博弈类算法。博弈树,二进制法等。
7.最大团,最大独立集。
8.判断点在多边形内。
9. 差分约束系统.
10. 双向广度搜索、A*算法,最小耗散优先.

相关的知识

图论

路径问题
0/1边权最短路径
BFS
非负边权最短路径(Dijkstra)
可以用Dijkstra解决问题的特征
负边权最短路径
Bellman-Ford
Bellman-Ford的Yen-氏优化
差分约束系统
Floyd
广义路径问题
传递闭包
极小极大距离 / 极大极小距离
Euler Path / Tour
圈套圈算法
混合图的 Euler Path / Tour
Hamilton Path / Tour
特殊图的Hamilton Path / Tour 构造

生成树问题
最小生成树
第k小生成树
最优比率生成树
0/1分数规划
度限制生成树

连通性问题
强大的DFS算法
无向图连通性
割点
割边
二连通分支
有向图连通性
强连通分支
2-SAT
最小点基

有向无环图
拓扑排序
有向无环图与动态规划的关系

二分图匹配问题
一般图问题与二分图问题的转换思路
最大匹配
有向图的最小路径覆盖
0 / 1矩阵的最小覆盖
完备匹配
最优匹配
稳定婚姻

网络流问题
网络流模型的简单特征和与线性规划的关系
最大流最小割定理
最大流问题
有上下界的最大流问题
循环流
最小费用最大流 / 最大费用最大流

弦图的性质和判定

组合数学

解决组合数学问题时常用的思想
逼近
递推 / 动态规划
概率问题
Polya定理

计算几何 / 解析几何

计算几何的核心:叉积 / 面积
解析几何的主力:复数

基本形

直线,线段
多边形

凸多边形 / 凸包
凸包算法的引进,卷包裹法

Graham扫描法
水平序的引进,共线凸包的补丁

完美凸包算法

相关判定
两直线相交
两线段相交
点在任意多边形内的判定
点在凸多边形内的判定

经典问题
最小外接圆
近似O(n)的最小外接圆算法
点集直径
旋转卡壳,对踵点
多边形的三角剖分

数学 / 数论

最大公约数
Euclid算法
扩展的Euclid算法
同余方程 / 二元一次不定方程
同余方程组

线性方程组
高斯消元法
解mod 2域上的线性方程组
整系数方程组的精确解法

矩阵
行列式的计算
利用矩阵乘法快速计算递推关系

分数
分数树
连分数逼近

数论计算
求N的约数个数
求phi(N)
求约数和
快速数论变换
……

素数问题
概率判素算法
概率因子分解

数据结构

组织结构
二叉堆
左偏树
二项树
胜者树
跳跃表
样式图标
斜堆
reap

统计结构
树状数组
虚二叉树
线段树
矩形面积并
圆形面积并

关系结构
Hash表
并查集
路径压缩思想的应用

STL中的数据结构
vector
deque
set / map

动态规划 / 记忆化搜索

动态规划和记忆化搜索在思考方式上的区别

最长子序列系列问题
最长不下降子序列
最长公共子序列
最长公共不下降子序列

一类NP问题的动态规划解法

树型动态规划

背包问题

动态规划的优化
四边形不等式
函数的凸凹性
状态设计
规划方向

线性规划

常用思想

二分 最小表示法

KMP Trie结构
后缀树/后缀数组 LCA/RMQ
有限状态自动机理论

排序
选择/冒泡 快速排序 堆排序 归并排序
基数排序 拓扑排序 排序网络

中级:
一.基本算法:
(1)C++的标准模版库的应用. (poj3096,poj3007)
(2)较为复杂的模拟题的训练(poj3393,poj1472,poj3371,poj1027,poj2706)
二.图算法:
(1)差分约束系统的建立和求解. (poj1201,poj2983)
(2)最小费用最大流(poj2516,poj2516,poj2195)
(3)双连通分量(poj2942)
(4)强连通分支及其缩点.(poj2186)
(5)图的割边和割点(poj3352)
(6)最小割模型、网络流规约(poj3308, )
三.数据结构.
(1)线段树. (poj2528,poj2828,poj2777,poj2886,poj2750)
(2)静态二叉检索树. (poj2482,poj2352)
(3)树状树组(poj1195,poj3321)
(4)RMQ. (poj3264,poj3368)
(5)并查集的高级应用. (poj1703,2492)
(6)KMP算法. (poj1961,poj2406)
四.搜索
(1)最优化剪枝和可行性剪枝
(2)搜索的技巧和优化 (poj3411,poj1724)
(3)记忆化搜索(poj3373,poj1691)

五.动态规划
(1)较为复杂的动态规划(如动态规划解特别的施行商问题等)
(poj1191,poj1054,poj3280,poj2029,poj2948,poj1925,poj3034)
(2)记录状态的动态规划. (POJ3254,poj2411,poj1185)
(3)树型动态规划(poj2057,poj1947,poj2486,poj3140)
六.数学
(1)组合数学:
1.容斥原理.
2.抽屉原理.
3.置换群与Polya定理(poj1286,poj2409,poj3270,poj1026).
4.递推关系和母函数.

(2)数学.
1.高斯消元法(poj2947,poj1487, poj2065,poj1166,poj1222)
2.概率问题. (poj3071,poj3440)
3.GCD、扩展的欧几里德(中国剩余定理) (poj3101)
(3)计算方法.
1.0/1分数规划. (poj2976)
2.三分法求解单峰(单谷)的极值.
3.矩阵法(poj3150,poj3422,poj3070)
4.迭代逼近(poj3301)
(4)随机化算法(poj3318,poj2454)
(5)杂题.
(poj1870,poj3296,poj3286,poj1095)
七.计算几何学.
(1)坐标离散化.
(2)扫描线算法(例如求矩形的面积和周长并,常和线段树或堆一起使用).
(poj1765,poj1177,poj1151,poj3277,poj2280,poj3004)
(3)多边形的内核(半平面交)(poj3130,poj3335)
(4)几何工具的综合应用.(poj1819,poj1066,poj2043,poj3227,poj2165,poj3429)

高级:
一.基本算法要求:
(1)代码快速写成,精简但不失风格
(poj2525,poj1684,poj1421,poj1048,poj2050,poj3306)
(2)保证正确性和高效性. poj3434
二.图算法:
(1)度限制最小生成树和第K最短路. (poj1639)
(2)最短路,最小生成树,二分图,最大流问题的相关理论(主要是模型建立和求解)
(poj3155, poj2112,poj1966,poj3281,poj1087,poj2289,poj3216,poj2446
(3)最优比率生成树. (poj2728)
(4)最小树形图(poj3164)
(5)次小生成树.
(6)无向图、有向图的最小环
三.数据结构.
(1)trie图的建立和应用. (poj2778)
(2)LCA和RMQ问题(LCA(最近公共祖先问题) 有离线算法(并查集+dfs) 和 在线算法
(RMQ+dfs)).(poj1330)
(3)双端队列和它的应用(维护一个单调的队列,常常在动态规划中起到优化状态转移的
目的). (poj2823)
(4)左偏树(可合并堆).
(5)后缀树(非常有用的数据结构,也是赛区考题的热点).
(poj3415,poj3294)
四.搜索
(1)较麻烦的搜索题目训练(poj1069,poj3322,poj1475,poj1924,poj2049,poj3426)
(2)广搜的状态优化:利用M进制数存储状态、转化为串用hash表判重、按位压缩存储状态、双向广搜、A*算法. (poj1768,poj1184,poj1872,poj1324,poj2046,poj1482)
(3)深搜的优化:尽量用位运算、一定要加剪枝、函数参数尽可能少、层数不易过大、可以考虑双向搜索或者是轮换搜索、IDA*算法. (poj3131,poj2870,poj2286)
五.动态规划
(1)需要用数据结构优化的动态规划.
(poj2754,poj3378,poj3017)
(2)四边形不等式理论.
(3)较难的状态DP(poj3133)
六.数学
(1)组合数学.
1.MoBius反演(poj2888,poj2154)
2.偏序关系理论.
(2)博奕论.
1.极大极小过程(poj3317,poj1085)
2.Nim问题.
七.计算几何学.
(1)半平面求交(poj3384,poj2540)
(2)可视图的建立(poj2966)
(3)点集最小圆覆盖.
(4)对踵点(poj2079)
八.综合题.
(poj3109,poj1478,poj1462,poj2729,poj2048,poj3336,poj3315,poj2148,poj1263)

初期:
一.基本算法:
(1)枚举. (poj1753,poj2965) (2)贪心(poj1328,poj2109,poj2586)
(3)递归和分治法. (4)递推.
(5)构造法.(poj3295) (6)模拟法.(poj1068,poj2632,poj1573,poj2993,poj2996)
二.图算法:
(1)图的深度优先遍历和广度优先遍历.
(2)最短路径算法(dijkstra,bellman-ford,floyd,heap+dijkstra)
(poj1860,poj3259,poj1062,poj2253,poj1125,poj2240)
(3)最小生成树算法(prim,kruskal)
(poj1789,poj2485,poj1258,poj3026)
(4)拓扑排序 (poj1094)
(5)二分图的最大匹配 (匈牙利算法) (poj3041,poj3020)
(6)最大流的增广路算法(KM算法). (poj1459,poj3436)
三.数据结构.
(1)串 (poj1035,poj3080,poj1936)
(2)排序(快排、归并排(与逆序数有关)、堆排) (poj2388,poj2299)
(3)简单并查集的应用.
(4)哈希表和二分查找等高效查找法(数的Hash,串的Hash)
(poj3349,poj3274,POJ2151,poj1840,poj2002,poj2503)
(5)哈夫曼树(poj3253)
(6)堆
(7)trie树(静态建树、动态建树) (poj2513)
四.简单搜索
(1)深度优先搜索 (poj2488,poj3083,poj3009,poj1321,poj2251)
(2)广度优先搜索(poj3278,poj1426,poj3126,poj3087.poj3414)
(3)简单搜索技巧和剪枝(poj2531,poj1416,poj2676,1129)
五.动态规划
(1)背包问题. (poj1837,poj1276)
(2)型如下表的简单DP(可参考lrj的书 page149):
1.E[j]=opt{D+w(i,j)} (poj3267,poj1836,poj1260,poj2533)
2.E[i,j]=opt{D[i-1,j]+xi,D[i,j-1]+yj,D[i-1][j-1]+zij} (最长公共子序列)
(poj3176,poj1080,poj1159)
3.C[i,j]=w[i,j]+opt{C[i,k-1]+C[k,j]}.(最优二分检索树问题)
六.数学
(1)组合数学:
1.加法原理和乘法原理.
2.排列组合.
3.递推关系.
(POJ3252,poj1850,poj1019,poj1942)
(2)数论.
1.素数与整除问题
2.进制位.
3.同余模运算.
(poj2635, poj3292,poj1845,poj2115)
(3)计算方法.
1.二分法求解单调函数相关知识.(poj3273,poj3258,poj1905,poj3122)
七.计算几何学.
(1)几何公式.
(2)叉积和点积的运用(如线段相交的判定,点到线段的距离等). (poj2031,poj1039)
(3)多边型的简单算法(求面积)和相关判定(点在多边型内,多边型是否相交)
(poj1408,poj1584)
(4)凸包. (poj2187,poj1113)

Posted in Computer Science & Engineer | Leave a comment

自拍

Posted in Computer Science & Engineer | Leave a comment