struct node {
int v, w;
bool operator>(const node &x)const {
return w > x.w;
}
};
vector<node>g[N];
bool vis[N];
int dis[N];
priority_queue<node, vector<node>, greater<node>>q;
void Prim() {
memset(dis, 0x4f, sizeof(dis));
dis[1] = 0;
int cnt = 0;
q.push({1, 0});
while (q.size()) {
int u = q.top().v, w = q.top().w;
q.pop();
if (vis[u])
continue;
vis[u] = 1;
cnt++;
ans += w;
if (cnt == n)
return;
for (auto t : g[u]) {
int v = t.v, w = t.w;
if (w < dis[v])
dis[v] = w, q.push(t);
}
}
}
Kruskal
C++
struct node {
int u,v,w;
bool opreator<(const node &x)const {
return w<x.w;
}
};
void kruskal(DSU &dsu) {
int cnt = 0;
for (auto t : g) {
int u = dsu.find(t.u), v = dsu.find(t.v);
if (u == v)
continue;
dsu.mergy(u, v);
cnt++;
ans += t.w;
if (cnt == n - 1)
return;
}
}
数据结构
并查集
C++
struct DSU {
vector<int>pa, size;
DSU (int n) {
pa.resize(n + 1);
size.resize(n + 1, 1);
for (int i = 1; i <= n; i++)
pa[i] = i;
}
int find(int x) {
return pa[x] == x ? x : pa[x] = find(pa[x]);
}
void mergy(int x, int y) {
x = find(x), y = find(y);
if (x == y)
return;
if (size[x] < size[y])
swap(x, y);
size[x] += size[y];
pa[y] = x;
}
};
线段树
C++
#define ll long long#define M ((L+R)>>1)
#define ls u*2#define rs u*2+1using namespace std;
const int N = 1e5+5;
int n, m, op, x, y;
ll a[N], k;
struct node {
ll w, lzy;
} tree[4 * N];
void pushup(int u) {
tree[u].w = tree[u * 2].w + tree[u * 2 + 1].w;
}
void build(int u, int L, int R) {
if (L == R) {
tree[u].w = a[L];
return;
}
build(ls, L, M);
build(rs, M + 1, R);
pushup(u);
}
void maketag(int u, int len, ll x) {
tree[u].lzy += x;
tree[u].w += len * x;
}
void pushdown(int u, int L, int R) {
maketag(ls, M - L + 1, tree[u].lzy);
maketag(rs, R - M, tree[u].lzy);
tree[u].lzy = 0;
}
bool inrange(int L, int R, int l, int r) {
return (L >= l) && (R <= r);
}
bool outrange(int L, int R, int l, int r) {
return (L > r) || (R < l);
}
ll caory(int u, int L, int R, int l, int r) {
if (inrange(L, R, l, r))
return tree[u].w;
else if (!outrange(L, R, l, r)) {
pushdown(u, L, R);
return caory(ls, L, M, l, r) + caory(rs, M + 1, R, l, r);
} elsereturn 0;
}
void update(int u, int L, int R, int l, int r, ll x) {
if (inrange(L, R, l, r))
maketag(u, R - L + 1, x);
else if (!outrange(L, R, l, r)) {
pushdown(u, L, R);
update(ls, L, M, l, r, x);
update(rs, M + 1, R, l, r, x);
pushup(u);
}
}