prim求调

P3366 【模板】最小生成树

Suin_tryin @ 2024-02-22 17:10:21

#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 5010;
int n, m, cnt, ans;
int dis[maxn], vis[maxn], head[maxn];
struct edge {
    int to, nxt, w;
}e[400010]; //双向边等于两条,容量*2;
void init() { //初始化
    for(int i = 1; i <= n; i ++)
        dis[i] = 1e9;
    memset(head, -1, sizeof(head));
    ans = 0;
}
void add(int u, int v, int w) { //链式前向星存边
    e[++cnt].to = v;
    e[cnt].w = w;
    e[cnt].nxt = head[u];
    head[u] = cnt;
}
void prim() { //prim算法
    dis[1] = 0;
    for(int i = 1; i <= n; i ++) {
        int k = 0;
        for(int j = 1; j <= n; j ++)
            if(!vis[j] && dis[j] < dis[k])
                k = j;
        vis[k] = 1;
        ans += dis[k];
        for(int j = head[k]; ~j; j = e[j].nxt) {
            int v = e[j].to;
            if(!vis[j] && dis[v] > e[j].w)
                dis[v] = e[j].w;
        }
    }
}
int main() {
    cin >> n >> m;
    init();
    for(int i = 1; i <= m; i ++) {
        int u, v, w;
        cin >> u >> v >> w;
        add(u, v, w);
        add(v, u, w); //双向边
    }
    prim(); //prim最小生成树算法
    if(ans == 0) cout << "orz" << endl;
    else cout << ans << endl;
    return 0;
}

样例输出了orz


by L_zaa_L @ 2024-02-22 17:16:16

#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 5010;
int n, m, cnt, ans;
int dis[maxn], vis[maxn], head[maxn];
struct edge {
    int to, nxt, w;
}e[400010]; //双向边等于两条,容量*2;
void init() { //初始化
    for(int i = 1; i <= n; i ++)
        dis[i] = 1e9;
    memset(head, -1, sizeof(head));
    ans = 0;
}
void add(int u, int v, int w) { //链式前向星存边
    e[++cnt].to = v;
    e[cnt].w = w;
    e[cnt].nxt = head[u];
    head[u] = cnt;
}
void prim() { //prim算法
    dis[1] = 0;
    dis[0]=1e9;//1.打擂台的时候初始值要大。 
    for(int i = 1; i <= n; i ++) {
        int k = 0;
        for(int j = 1; j <= n; j ++)
            if(!vis[j] && dis[j] < dis[k])
                k = j;
        vis[k] = 1;
        ans += dis[k];
        for(int j = head[k]; ~j; j = e[j].nxt) {
            int v = e[j].to;
            if(!vis[v] && dis[v] > e[j].w)//2.是vis[v]而不是vis[j] 
                dis[v] = e[j].w;//3.是e[j].w!
        }
    }
}
int main() {
    cin >> n >> m;
    init();
    for(int i = 1; i <= m; i ++) {
        int u, v, w;
        cin >> u >> v >> w;
        add(u, v, w);
        add(v, u, w); //双向边
    }
    prim(); //prim最小生成树算法
    if(ans == 0) cout << "orz" << endl;
    else cout << ans << endl;
    return 0;
}

by L_zaa_L @ 2024-02-22 17:16:30

@Suin_tryin


by Suin_tryin @ 2024-02-22 17:32:48

非常感谢,现在已经AC了

prim()里还要加一个特判,不然改了以后 #13 还是过不了

if(k == 0) {
    ans = 0;
    break;
}

|