NOIP前模板整理

时间:2024-12-07 17:33:45

最短路径

#include <queue>
#define N 1000
typedef long long ll;
using namespace std;
int d[N], w[N][N], num[N];
ll dis[N];
queue<int> que;
void spfa(){
for (int i=;i<=n;i++) dis[i]=0x7fffff;
que.push();d[]=;dis[]=;
do{
int h=que.front();
d[h]=,que.pop();
for (int i=,v;i<=num[h];i++){
v = s[h][i];
if (dis[v] > dis[h] + w[h][s[v]]) {
dis[v] = dis[h] + w[h][v];
if (!d[v]) que.push(v),d[v]=;
}
}
}while(!que.empty())
}

spfa

void floyd(){
for (int k=;k<=n;k++) {
for (int i=;i<=n;i++) {
for (int j=;j<=n;j++){
if (a[i][j] > a[i][k]+a[k][j]){
a[i][j] = a[i][k]+a[k][j];
}
}
}
}
}

floyd

struct Node {
int id,dis;
bool operator < (const Node& rhs) const{
return dis>rhs.dis;
}
};
priority_queue<Node> q; int vis[N],dis[N];
void dijkstra(int s){
q.push((Node){s,});
while(!q.empty()) {
int u=q.top().id;
if(vis[u]) continue;
vis[u]=;
trav(u,i) {
int v=e[i].v;
if(dis[v]>dis[u]+e[i].w) {
dis[v]=dis[u]+e[i].w;
q.push((Node){v,dis[v]});
}
}
}
}

dijkstra

LCA

#define N 100005
#define D 21
struct Edge {
int v,nxt;
}e[M];
int en=,front[N];
void adde(int u,int v){
e[++en]=(Edge){v,front[u]}; front[u]=en;
} int fa[N][D],dep[N]; void dfs(int u){
for(int i=;i<D;i++)
fa[u][i]=fa[fa[u][i-]][i-];
trav(u,i) {
int v=e[i].v;
if(v!=fa[u][]) {
fa[v][]=u;
dep[v]=dep[u]+;
dfs(v);
}
}
}
int lca(int u,int v)
{
if(dep[u]<dep[v]) swap(u,v);
int t=dep[u]-dep[v];
for(int i=;i<D;i++)
if(t&(<<i)) u=fa[u][i];
if(u==v) return u;
for(int i=D-;i>=;i--)
if(fa[u][i]!=fa[v][i])
u=fa[u][i],v=fa[v][i];
return fa[u][];
}
int main(){
//input
while(t--){
scanf("%d%d", &u,&v);
printf("%d\n", dep[u]+dep[v]-*dep[lca(u,v)]);
}
}

倍增

RMQ

#include <iostream>
#include <cstdio>
#include <cmath>
#define maxn 50005
using namespace std;
int x, y, t, s, k;
int fa[maxn][], fi[maxn][], n, q, a[maxn];
void rmq(){
for (int i=;i<=n;i++) fa[i][] = a[i], fi[i][] = a[i];
for (int i=;i<=floor(log(n)/log());i++)
for (int j=;j<=n+-(<<i);j++){
fa[j][i] = max(fa[j][i-], fa[j+(<<i-)][i-]);
fi[j][i] = min(fi[j][i-], fi[j+(<<i-)][i-]);
}
}
int main(){
while(scanf("%d%d", &n,&q)!=EOF){
for (int i=;i<=n;i++) scanf("%d",&a[i]);
rmq();
for (int i=;i<=q;i++){
scanf("%d%d",&x,&y);
k = (int)(log(y-x+1.0)/log(2.0));
t=max(fa[x][k],fa[y-(<<k)+][k]),s=min(fi[x][k],fi[y-(<<k)+][k]);
printf("%d\n",t-s);
}
}
return ;
}

rmq

输入输出优化

void read(int& x) {
char c=getchar();
while(!isdigit(c)) c=getchar();
x=;
while(isdigit(c)) x=x*+c-'' , c=getchar();
}

read()