克鲁斯卡尔算法(本质:边的排序+并查集判断是否成环)
代码模板:
typedef struct node {
int u,v;//克鲁斯卡尔需要边 但是不需要图
int len;
}node;
vector<node> edges;
int n,m;
int bs[105];//并查集
//find
int ask(int ch) {
if(bs[ch]==ch) {
return ch;
}else {
return bs[ch]=ask(bs[ch]);
}
}
//union
void join(int x,int y) {
bs[ask(y)]=ask(x);
}
bool comp(node &a,node& b) {
return a.len<b.len;
}
int krs() { //克鲁斯卡尔算法
int tot=0;
sort(edges.begin(),edges.end(),comp);
for(int i=0;i<edges.size();i++) {
node fa=edges[i];//当然可以在收集到了n-1条边时跳出
if(ask(fa.u) != ask(fa.v)) {
tot+=fa.len;
join(fa.u,fa.v);
}
}
return tot;
}
普里姆算法:(本质:bfs[优先级队列] + has数组判断点是否在队列之内 )需要有图
代码模板:
typedef struct node {
int at;
int len;
bool operator< (const node &n) const {
return len>n.len;
}
}node;
int n,m;
vector<node> mp[105];
int has[105],hasnum=0;
int prm(int start) {
int tot=0;
priority_queue<node> pq;
node d; d.at=start; d.len=0;
pq.push(d);
while(!pq.empty()) {
node fa=pq.top(); pq.pop();
has[fa.at]=1; hasnum++; tot+=fa.len;
if(hasnum==n) break;//收集到了足够的点跳出
for(int i=0;i<mp[fa.at].size();i++) {
node ch=mp[fa.at][i];
if(has[ch.at]==0) {
pq.push(ch);
}
}
}
return tot;
}