求MST的最长边~
prim
#include <cstdio> #include <cstring> #include <vector> #include <algorithm> #define Min(a,b) (a)<(b)?(a):(b) using namespace std; const int INF = 1000000000; const int maxn = 2000 + 5; struct pto { int v, len; }; vector<pto> G[maxn]; bool vis[maxn]; int dis[maxn]; int n, m; int Prim() { int i, j, p, ans, minc; memset(vis, 0, sizeof vis ); for(i=1; i<=n; ++i) dis[i] = INF; dis[1] = 0; ans = 0; int maxx = -100; for(i=1; i<=n; ++i) { minc = INF, p = -1; for(j=1; j<=n; ++j) if(!vis[j]) if(minc>dis[j]) minc = dis[p=j]; if(-1 == p) break; vis[p] = 1; if(maxx <minc) maxx = minc; for(j=0; j<G[p].size(); ++j) if(!vis[G[p][j].v]) { int& u = G[p][j].v; dis[u] = Min(dis[u], G[p][j].len); } } return maxx; } int main() { int i, x, y, z; pto e; while(~scanf("%d%d",&n,&m)) { for(i=0; i<=n; ++i) G[i].clear(); for(i=0; i<m; ++i) { scanf("%d%d%d",&x,&y,&z); e.v = y, e.len = z; G[x].push_back(e); e.v = x; G[y].push_back(e); } printf("%d\n",Prim()); } return 0; }
kruskal
#include <cstdio> #include <cstring> #include <vector> #include <algorithm> using namespace std; const int INF = 1000000000; const int maxn = 2000 + 5; const int maxm = 10000 + 5; struct Edge { int x, y, w; Edge(int x=0, int y=0, int w=0):x(x),y(y),w(w) {} bool operator < (const Edge& rhs) const { return w < rhs.w; } } e[maxm]; int fa[maxn]; int n, m; int getfather(int x) { while(x != fa[x]) x = fa[x]; return fa[x]; } int kruskal() { int i, t1, t2, ans = 0, num = 0; int maxx = -100; sort(e, e+m); for(i=1; i<=n; ++i) fa[i] = i; for(i=0; i<m; ++i) { t1 = getfather(e[i].x); t2 = getfather(e[i].y); if(t1 != t2) { fa[t1] = t2; ans += e[i].w; if(maxx<e[i].w) maxx = e[i].w; if(++num==n-1) break; } } return maxx; } int main() { int i, x, y, z; while(~scanf("%d%d",&n,&m)) { for(i=0; i<m; ++i) { scanf("%d%d%d",&e[i].x, &e[i].y, &e[i].w); } printf("%d\n", kruskal()); } return 0; }
poj2395 Out of Hay , 求MST的最长边,布布扣,bubuko.com
时间: 2024-10-22 11:32:10