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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章