模板題——堆排序 雜湊表 字串雜湊
阿新 • • 發佈:2021-02-02
技術標籤:演算法基礎模板
1.堆排序
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int n,m;
int h[N],sizee;
void down(int u)
{
int t=u;
if(u*2<=sizee&&h[u*2]<h[t]) t=u*2;
if(u*2+1<=sizee&&h[u*2+1]<h[t]) t=u*2+1;
if(u!=t)
{
swap(h[u],h[ t]);
down(t);
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&h[i]);
sizee=n;
for(int i=n/2;i!=0;i--) down(i);//建堆
while(m--)
{
printf("%d ",h[1]);//輸出最小值
h[1]=h[sizee];//刪除最小值
sizee-- ;
down(1);
}
return 0;
}
2.模擬堆
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int h[N],hp[N],ph[N],sizee;
void heap_swap(int a,int b)//堆裡特有的對映排序
{
swap(ph[hp[a]],ph[hp[b]]);
swap(hp[a],hp[b]);
swap(h[a],h[b]);
}
void down(int u)
{
int t=u;
if(u* 2<=sizee&&h[u*2]<h[t]) t=u*2;
if(u*2+1<=sizee&&h[u*2+1]<h[t]) t=u*2+1;
if(u!=t)
{
heap_swap(u,t);
down(t);
}
}
void up(int u)
{
while(u/2!=0&&h[u/2]>h[u])
{
heap_swap(u/2,u);
u/=2;
}
}
int main()
{
int n,m=0;
scanf("%d",&n);
while(n--)
{
char op[10];
int k,x;
scanf("%s",op);
if(!strcmp(op,"I"))//插入操作
{
scanf("%d",&x);
sizee++;
m++;
ph[m]=sizee;
hp[sizee]=m;
h[sizee]=x;
up(sizee);
}
else if(!strcmp(op,"PM")) printf("%d\n",h[1]);
else if(!strcmp(op,"DM"))
{
heap_swap(1,sizee);
sizee--;
down(1);
}
else if(!strcmp(op,"D"))//刪除第k個插入的元素
{
scanf("%d",&k);
k=ph[k];
heap_swap(k,sizee);
sizee--;
down(k),up(k);
}
else//修改第k個插入的數,將其變為x;
{
scanf("%d%d",&k,&x);
k=ph[k];
h[k]=x;
down(k),up(k);
}
}
return 0;
}
3.模擬散列表
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int h[N],e[N],ne[N],idx;
void insertt(int x)
{
int k=(x%N+N)%N;
e[idx]=x;
ne[idx]=h[k];
h[k]=idx++;
}
bool findd(int x)
{
int k=(x%N+N)%N;
for(int i=h[k];i!=-1;i=ne[i])
if(e[i]==x) return true;
return false;
}
int main()
{
int n;
scanf("%d",&n);
memset(h,-1,sizeof(h));
while(n--)
{
char op[2];
int x;
scanf("%s%d",op,&x);
if(*op=='I') insertt(x);
else
{
if(findd(x)) puts("Yes");
else puts("No");
}
}
return 0;
}
4.字串雜湊
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
const int N=100010,P=131;
int n,m;
char str[N];
ULL h[N],p[N];
ULL gett(int l,int r)//字串雜湊公式
{
return h[r]-h[l-1]*p[r-l+1];
}
int main()
{
scanf("%d%d%s",&n,&m,str+1);
p[0]=1;
for(int i=1;i<=n;i++)
{
p[i]=p[i-1]*P;
h[i]=h[i-1]*P+str[i];
}
while(m--)
{
int l1,r1,l2,r2;
scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
if(gett(l1,r1)==gett(l2,r2)) puts("Yes");
else puts("No");
}
return 0;
}