朴素prim,O(n^2),洛谷板子题519ms
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int maxn = 5e3+5;
int mmp[maxn][maxn];
int dis[maxn],n,m,ans;
bool vis[maxn];
void init(int n){
for(int i=0;i<=n;i++)
for(int j=0;j<=n;j++)
mmp[i][j] = inf;
}
void prim(int x){
for(int i=1;i<=n;i++)
dis[i] = mmp[x][i];
vis[x] = 1;
for(int i=1;i<n;i++){
int idx = 0,minn = inf;
for(int j=1;j<=n;j++){
if(!vis[j] && minn > dis[j]){
idx = j,minn = dis[j];
}
}
if(!idx){
printf("orz\n");
return;
}
vis[idx] = 1;
ans += dis[idx];
for(int j=1;j<=n;j++){
if(!vis[j] && dis[j] > mmp[idx][j]){
dis[j] = mmp[idx][j];
}
}
}
printf("%d\n",ans);
}
int main(){
scanf("%d%d",&n,&m);
init(n);
for(int i=0;i<m;i++){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
if(mmp[x][y]>z){
mmp[x][y] = mmp[y][x] = z;
}
}
prim(1);
return 0;
}
堆优化(优先队列),vector,pair,存图prim O(m*log(m)),o2优化后219ms,相当于手写堆
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<pair<int,int> > E[200005];
int dis[100005],ans,cnt,n,m;
bool vis[100005];
void init(int n,int m)
{
for(int i=0;i<=n;i++)dis[i] = 1e9;
for(int i=0;i<=m;i++)E[i].clear();
}
void prim(int s){
priority_queue<pair<int,int> > Q;
vis[s] = 1;
for(int i=0;i<E[s].size();i++)
Q.push(make_pair(-E[s][i].second,E[s][i].first));
while(!Q.empty() && cnt<n-1)
{
int now = Q.top().second;
int wit = -Q.top().first;
Q.pop();
if(vis[now])continue;
vis[now] = 1;
cnt++;
ans += wit;
for(int i=0;i<E[now].size();i++)
{
int v = E[now][i].first;
int x = E[now][i].second;
if(!vis[v])
Q.push(make_pair(-x,v));
}
}
if(cnt!=n-1)
printf("orz\n");
else
printf("%d\n",ans);
}
int main() {
scanf("%d%d",&n,&m);
init(n,m);
for(int i=0;i<m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
E[x].push_back(make_pair(y,z));
E[y].push_back(make_pair(x,z));
}
prim(1);
return 0;
}
并查集优化kruskal(一般的kruskal),O( m*log(m) +m*Ackermann’(m)),Ackermann’函数增长太慢了,所以看成常数,
所以可以看成O(m*log(m))
200ms,o2优化148ms
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxm = 2e5+7;
const int maxn = 5e3+5;
struct Edg{
int u,v,w;
bool operator < (const Edg &a) const{
return w<a.w;
}
}E[maxm];
int p[maxn];
void init(){
for(int i=0;i<maxn;i++)
p[i] = i;
}
void Merge(int x,int y){
p[x] = y;
}
int Find(int x){
return x == p[x] ? x : p[x] = Find(p[x]) ;
}
int main(){
init();
int n,m,cnt = 0,ans = 0;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].w);
}
sort(E,E+m);
for(int i=0;cnt<n-1 && i<m;i++){
int tx = Find(E[i].u);
int ty = Find(E[i].v);
if(tx!=ty){
Merge(tx,ty);
ans += E[i].w;
cnt++;
}
}
if(cnt!=n-1)
printf("orz\n");
else
printf("%d\n",ans);
return 0;
}