POJ - 1251Jungle Roads prim()

只想静静的水题。prim

#include <stdio.h>
#include <string.h>
#include <iostream>
#include<algorithm>
#include <vector>
#include <queue>
#include <string>
#include <math.h>
#include <stdlib.h>
using namespace std;
#define INF 0x3f3f3f3f
#define mem(arr,a) memset(arr,a,sizeof(arr))
#define V 200+5
#define LL long long int
#define E 320000
#define pow(a) ((a)*(a))
int n, m;
int cost[V][V];
int minCost[V];
int vis[V];
int sum;
void prim(){
    for (int i = 1; i <= n; i++){
        minCost[i] = cost[1][i];
        vis[i] = 0;
    }
    while (1){
        int v = -1;
        for (int i = 1; i <= n; i++){
            if (!vis[i] && (v == -1 || minCost[i] < minCost[v]))v = i;
        }
        if (v == -1)break;
        vis[v] = 1;
        sum += minCost[v];
        for (int i = 1; i <= n; i++){
            if (minCost[i]>cost[v][i])minCost[i] = cost[v][i];
        }
    }
    cout << sum << endl;

}
int main(){
    while (cin >> n)
    {
        if (n == 0)break;
        sum = 0;
        mem(cost, INF);
        for (int i = 1; i < n; i++){
            char s; int t;
            cin >> s >> t;
            while (t--){
                char str; int cos;
                cin >> str >> cos;
                cost[i][str - 'A' + 1] = cost[str - 'A' + 1][i] = cos;
            }
            cost[i][i] = 0;
        }
        prim();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值