〇 单调栈
stack<int> stk; //单调递增栈
void insert(int x)
{
while(!stk.empty() && stk.top() > x)
stk.pop();
stk.push(x);
}
〇 单调队列
deque<int> q;
void insert(int x)
{
while(!q.empty() && q.back() < x)
q.pop_back();
q.push_back(x);
}
〇 滑动窗口
〇 kmp算法
void getnext(string &t)
{
int i = 0;k = -1;
next[0] = -1;
while(i < t.size())
{
if(k == -1 || t[i] = t[k]) next[++i] = ++k;
else k = next[k];
}
}
int kmp(string &s , string &t)
{
int i = 0,j = 0;
while(i < s.size() && j < (int)t.size())
{
if(j == -1 || s[i] = t[j]) i++,j++;
else j = next[j];
}
if(j == t.size()) return i - j;
else return -1;
}
〇 优化next数组
void getnextval(int nextval[],string &t)
{
int i = 0,k = -1;
nexxtval[0] = -1;
while(i < t.size() - 1)
{
if(k == -1 || t[k] == t[i])
{
if(t[++k] != t[++i]) nextval[i] = k;
else nextval[i] = nextval[k];
}
else k = nextval[k];
}
}
〇 寻找所有的模式串
vector<int> getPrefix(string &t)
{
int m = t.size();
vector<int> Pi(m);
for(int i = 1;i < m;i++)
{
int k = Pi[i - 1];
while(k && t[k] != t[i]) k = Pi[k - 1]
if(t[k] == t[i]) k++;
Pi[i] = k;
}
return Pi;
}
vector<int> kmp(string &s,string &t)
{
int n = s.size(),m = t.size();
string r = t + '#' + s;
Pi[m] = getPrefix( t );
vector<int> res;
for(int i = m + 1;i <= n + m;i++)
if(Pi[i] == m) res.push_back(i - 2 * m);
return res;
}
〇 寻找所有的模式串的kmp算法
vector<int> getPrefix(string &t)
{
int m = t.size();
vector<int> Pi(m);
for(int i = 1;i < m;i++)
{
int k = Pi[i - 1];
while(k && t[k] != t[i]) k = Pi[k - 1]
if(t[k] == t[i]) k++;
Pi[i] = k;
}
return Pi;
}
vector<int> kmp(string &s,string &t)
{
int n = s.size(),m = t.size();
string r = t + '#' + s;
Pi[m] = getPrefix( t );
vector<int> res;
for(int i = m + 1;i <= n + m;i++)
if(Pi[i] == m) res.push_back(i - 2 * m);
return res;
}
〇 并查集
int find(int x) //找到x所在集合
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
void merge(int a,int b) //合并两个集合
{
int pa = find(a);
int pb = find(b);
if(pa != pb)
p[pa] = pb;
}
void query(int a,int b) //询问a,b是否在同一集合
{
int pa = find(a);
int pb = find(b);
if(pa == pb) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
〇 模拟堆
void down(int u)
{
int t = u;
if( 2*u <= idx && h[ 2*u ] < h[t] ) t = 2*u;
if( 2*u + 1 <= idx && h[ 2*u + 1] < h[t]) t = 2*u + 1;
if( u != t ) swap(h[u],h[t])
}
void up(int u)
{
while( u/2 && h[u/2] > h[u])
{
swap(h[u],h[u/2])
u/2;
}
}
欢迎订阅专栏,数据结构实验,期末大作业,前端后端,算法都有哦,想我发哪个方面的资源或文章可以私信我,免费的哦