POJ:1751 Highways
2013-10-09 12:45
281 查看
最小生成树。这个题POJ上要用G++交,C++会超时。再就是注意到是special judge就行了,
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #define MAXN 1000 using namespace std; struct Edge { int a,b; double weight; }; struct Point { int x,y; }; int father[MAXN]; int find(int p) { return p==father[p]?p:(father[p]=find(father[p])); } double Dist(Point a,Point b) { double ll=(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y); return sqrt(ll); } bool cmp(Edge a,Edge b) { return a.weight<b.weight; } Edge e[MAXN*MAXN]; Point po[MAXN]; int main() { int n,m; while(scanf("%d",&n)!=EOF&&n) { for(int i=1; i<=n; ++i) scanf("%d%d",&po[i].x,&po[i].y); scanf("%d",&m); int u,v; for(int i=0; i<=n; ++i) father[i]=i; for(int i=0; i<m; ++i) { scanf("%d%d",&u,&v); if(find(u)!=find(v)) father[find(u)]=find(v); } int N=0,cou=0; for(int i=1; i<n; ++i) for(int j=i+1; j<=n; ++j) { e .a=i; e .b=j; e[N++].weight=Dist(po[i],po[j]); } sort(e,e+N,cmp); Edge ans[MAXN]; for(int i=0; i<N; ++i) { int ta=find(e[i].a),tb=find(e[i].b); if(ta!=tb) { father[ta]=tb; printf("%d %d\n",e[i].a,e[i].b); cou++; if(cou>n-1) break; } } if(cou) printf("\n"); } return 0; }
相关文章推荐
- POJ-1751 Highways
- POJ 1751 - Highways(最小生成树)
- POJ - 1751 Highways
- 【POJ 1751】Highways(最小生成树-水题)
- poj 1751 Highways(Kruskal)
- POJ 1751 Highways(kuangbin带你飞 专题六:最小生成树)
- POJ-1751 Highways
- Poj --1751 highways (最小生成树,kruskal算法)
- POJ-1751-Highways [最小生成树]
- (搬运) poj 1751(Highways)+最小生成树两种算法
- poj 1751 Highways(Kruskal)
- POJ1751 Highways
- POJ 1751 Highways 最小生成树
- POJ 1751 Highways 最小生成树 Kruskal && Prim
- poj1751 Highways
- POJ 1751 Highways 最小生成树
- (搬运) poj 1751(Highways)+最小生成树两种算法
- poj 1751 Highways(Kruskal)
- POJ1751_Highways(最小生成树)
- poj-1751-Highways-最小生成树