最大生成树

const int inf = 1<<29;
int n, m;
int edge[1005][1005];
int d[1005];
bool vis[1005];

struct node
{
    int v, c;
    node(int _v, int _c):v(_v), c(_c){}
    friend bool operator< (node n1, node n2){
        return n1.c < n2.c;
    }
};
int ans;
void prim(){
    ans = inf;
     priority_queue<node>que;
    for(int i = 1; i <= n; i++){
        d[i] = edge[1][i];
        if (d[i]) que.push(node(i, d[i]));
    }
    d[1] = inf;
    memset(vis, false, sizeof(vis));
   
    
    while(!que.empty()){
        node tem = que.top();
        que.pop();
        
        int v = tem.v;
        int c = tem.c;
        ans = min(ans, c);
        if (v == n) return;
        if (vis[v]) continue;
        vis[v] = true;
        
        for(int i = 1; i <= n; i++){
            if (!vis[i] && edge[v][i] > d[i]){
                d[i] = edge[v][i];
                que.push(node(i, d[i])); 
            }
        }
    }
}

int main() {
    int t;
    int a, b, c;
    int k = 1;
    
    cin >> t;
    while(t--){
        scanf("%d%d", &n, &m);
        memset(edge, 0, sizeof(edge)); 
        for(int i = 1; i <= m; i++){
            scanf("%d%d%d", &a, &b, &c);
            edge[a][b] = edge[b][a] = c;        
        }
        prim();
        printf("Scenario #%d:
", k++);
        printf("%d

", ans);
    }

    return 0;
}
东北日出西边雨 道是无情却有情
原文地址:https://www.cnblogs.com/ccut-ry/p/7807777.html