NOIP 边权差值最小的生成树(小数据)
2017-07-15 15:22
232 查看
NOIP 边权差值最小的生成树(小数据)
2017年7月15日
Kruskal算法
因为根据Kruskal算法的原理,最小生成树的最短边确定后,最长边也相应确定,他们的差值就确定(参见《算法导论》)。所以可以枚举最短边求出生成树。
仅限小数据。
2017年7月15日
Kruskal算法
因为根据Kruskal算法的原理,最小生成树的最短边确定后,最长边也相应确定,他们的差值就确定(参见《算法导论》)。所以可以枚举最短边求出生成树。
仅限小数据。
#include<iostream> #include<cstdio> #include<string> #include<algorithm> #include<cstring> using namespace std; int N, M; struct Edges{ int x, y, v; }V[4000]; int ans = 0; int MinDif = 52013140; // int FatherVertex[500]; bool cmp(Edges a, Edges b){return a.v < b.v;} inline void UnionVertex(int a, int b){ FatherVertex[FatherVertex[a]] = FatherVertex[b];} inline void ResetFatherVertex(){ for(int i = 1; i <= N; i++) FatherVertex[i] = i;} inline int GetFatherVertex(int a){ if(FatherVertex[a] == a) return a; FatherVertex[a] = GetFatherVertex(FatherVertex[a]); return FatherVertex[a]; } void Putin() { cin >> N >> M; memset(FatherVertex, -1, sizeof(FatherVertex)); int a, b, c; for(int i = 1; i <= M; i++){ cin >> a >> b >> c; V[++ans].x = a; V[ans].y = b; V[ans].v = c; } for(int i = 1; i <= N; i++) FatherVertex[i] = i; sort(V + 1, V + 1 + M, cmp); } void Kruskal(int T) { ResetFatherVertex(); int upEdge = -1, downEdge = 100000; int sum = 0; for(int i = T; i <= M; i++){ if(GetFatherVertex(V[i].x) != GetFatherVertex(V[i].y)){ UnionVertex(V[i].x, V[i].y); upEdge = max(upEdge, V[i].v); downEdge = min(downEdge, V[i].v); sum++; } } if(sum == N - 1) MinDif = min(abs(upEdge - downEdge), MinDif); } int main() { Putin(); for(int i = 1; i <= M - N + 1; i++) Kruskal(i); if(MinDif > 42012140){ cout << -1 << endl; return 0; } cout << MinDif << endl; return 0; }
相关文章推荐
- (使用STL自带的排序功能进行排序7.3.12)UVA 11057 Exact Sum(在一组数据中找到这么两个数,使得他们的和等于指定数&&且这两个数之间的差值最小)
- POJ3522差值最小的生成树
- 两个数组,交互他们之间的数据,使得他们之间的差值最小
- POJ 3522 最大边与最小边差值最小的生成树(最小生成树的性质)
- 将文本文件中的数据读取到一个二维数组中,求出这些数据的中位数,然后求所有数据与中位数的差值的绝对值和,并求出和的最小值,最后把程序运行的结果写到一个txt文件中
- Slim Span 求一颗生成树 使得最大边与最小边的差值最小
- POJ 3522 最大边与最小边差值最小的生成树
- 数据结构之(图之最小生成树)Kruskal(克鲁斯卡尔)算法
- 【数据结构与算法】图之最小生成树
- POJ3522Slim Span(最大边与最小边差值最小的生成树)
- PKU3522(Slim Span)-求差值最小的生成树
- poj3522 Slim Span 最长边与最短边差值最小的生成树,kruskal算法 + 暴力枚举
- Poj 3522 最长边与最短边差值最小的生成树
- poj3522(求最大边最小边差值最小的生成树)
- 【poj3522-苗条树】最大边与最小边差值最小的生成树,并查集
- HDU 4081 Qin Shi Huang's National Road System(最小生成树/次小生成树)
- NOIP2013货车运输(最大生成树+LCA)
- 要从5个人中选取2个人作为礼仪,其中每个人的身高范围为160-190,要求2个人的身高差值最小(如果差值相同的话,选取其中最高的两人),以升序输出两个人的身高。
- UVA 10600 ACM Contest and Blackout(最小生成树and次小生成树)
- 最小生成树&&次小生成树