POJ 1751 Highways (ZOJ 2048 ) MST
http://poj.org/problem?id=1751
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2048
题目大意:
给你n个点的坐标,并且m个点之间已经建立起连接,让你输出剩下的MST的连接点。
两题其实一样。就输入一点点不同。
因为题目采用Special Judge故水题一题。
POJ:
#include<cstdio> #include<cmath> #include<algorithm> using namespace std; const int MAXN=755; const int INF=9999999; int fa[MAXN]; struct point { double x,y; }ship[MAXN]; struct dot { int x,y; double dis; }dis[MAXN*MAXN]; int find(int cur) { return fa[cur]==cur?cur:fa[cur]=find(fa[cur]); } bool operator < (const dot &a,const dot& b) { return a.dis<b.dis; } int main() { int n,kase=1; while(~scanf("%d",&n)) { if(kase!=1) printf("\n"); kase++; int i,j; for(i=1;i<=n;i++) scanf("%lf%lf",&ship[i].x,&ship[i].y); int len=0; for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { dis[len].x=i; dis[len].y=j; dis[len].dis=sqrt((ship[j].y -ship[i].y) *(ship[j].y -ship[i].y) + (ship[j].x -ship[i].x)*(ship[j].x -ship[i].x)); len++; } } for(i=1;i<=n;i++) fa[i]=i; int m; scanf("%d",&m); for(i=1;i<=m;i++) { int x,y; scanf("%d%d",&x,&y); int rootx=find(x); int rooty=find(y); fa[rootx]=rooty; } sort(dis,dis+len); for(i=0;i<len;i++) { int rootx=find(dis[i].x); int rooty=find(dis[i].y); if(rootx!=rooty) { printf("%d %d\n",dis[i].x,dis[i].y); fa[rootx]=rooty; } } } return 0; }
ZOJ:
#include<cstdio> #include<cmath> #include<algorithm> using namespace std; const int MAXN=755; const int INF=9999999; int fa[MAXN]; struct point { double x,y; }ship[MAXN]; struct dot { int x,y; double dis; }dis[MAXN*MAXN]; int find(int cur) { return fa[cur]==cur?cur:fa[cur]=find(fa[cur]); } bool operator < (const dot &a,const dot& b) { return a.dis<b.dis; } int main() { int T,n,kase=1; scanf("%d",&T); while(T--) { if(kase!=1) printf("\n"); kase++; scanf("%d",&n); int i,j; for(i=1;i<=n;i++) scanf("%lf%lf",&ship[i].x,&ship[i].y); int len=0; for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { dis[len].x=i; dis[len].y=j; dis[len].dis=sqrt((ship[j].y -ship[i].y) *(ship[j].y -ship[i].y) + (ship[j].x -ship[i].x)*(ship[j].x -ship[i].x)); len++; } } for(i=1;i<=n;i++) fa[i]=i; int m; scanf("%d",&m); for(i=1;i<=m;i++) { int x,y; scanf("%d%d",&x,&y); int rootx=find(x); int rooty=find(y); fa[rootx]=rooty; } sort(dis,dis+len); for(i=0;i<len;i++) { int rootx=find(dis[i].x); int rooty=find(dis[i].y); if(rootx!=rooty) { printf("%d %d\n",dis[i].x,dis[i].y); fa[rootx]=rooty; } } } return 0; }
新 blog : www.hrwhisper.me