poj2485-Highways

poj2485-Highways

求最小生成树的最大边。
Prim算法:每次将到已有的生成树点集距离最小的点加入到生成树点集中。时间复杂度:O(|E|log|V|)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
#define pir pair<int, int>
const int INF = 0x7fffffff;
const int MAXN = 505;

int read(){
    int k = 1, x = 0; char ch = getchar();
    while (ch<'0'||ch>'9') {
      if (ch == '-') k = -1;
      ch = getchar();
    }
    while ('0'<=ch&&ch<='9') {
      x = x * 10 + ch - '0';
      ch = getchar();
    }
    return k * x;
}

int cntEdge;

struct Edge{
    int t, w, next;
}map[1000000];

void addEdge(int x, int y, int z){
    map[++cntEdge].t = y;
    map[cntEdge].w = z;
    map[cntEdge].next = map[x].next;
    map[x].next = cntEdge;
}

int vis[MAXN], dis[MAXN], n;

bool operator < (const pir &x, const pir &y){
    return x.first < y.first;
}

bool cmp(const pir &x, const pir &y){
    return x.first < y.first;
}

int Prim(){
    memset(vis, 0, sizeof vis);
    for (int i = 1; i <= n; ++i) dis[i] = INF;
    dis[1] = 0;
    priority_queue<pir, vector<pir >, greater<pir> > q;
    q.push(make_pair(0, 1));
    int res = 0, tot = 0;
    while (tot <= n-1) {
      pir u = q.top();
      q.pop();
      if (vis[u.second]) continue;
      vis[u.second] = 1, tot++;
      res = max(res, u.first);
      for (int i = map[u.second].next; i != -1; i = map[i].next) {
        if (dis[map[i].t] <= map[i].w) continue;
        dis[map[i].t] = map[i].w;
        q.push(make_pair(dis[map[i].t], map[i].t));
      }
    }
    return res;
}

int main()
{
    int T = read(), x;
    while (T--) {
      n = read();
      for (int i = 1; i <= n; ++i) map[i].next = -1, map[i].w = 0, map[i].t = i; 
      cntEdge = n;
      for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j) {
          x = read();
          if (i != j) addEdge(i, j, x);
      }
      printf("%d\n", Prim());
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值