ZOJ 2048 Highways【kruskal】

94 篇文章 0 订阅
12 篇文章 0 订阅
2623181 	2011-08-11 21:41:26 	Accepted 	2048 	C++ 	910 	3492 	ylwh@Unknown

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>      
using namespace std;  
#define N 751
#define M 1001
struct node
{
        int x, y, root;
}s[N];
struct edge
{
        int len, x, y;
}e[N*N/2];
int cmp(struct edge a, struct edge b)
{   
   return a.len < b.len;
}
int cmp2(struct edge a, struct edge b)
{   
   return a.x < b.x;
}
int find_root(int x)
{
        int temp = x;;
        while(x != s[x].root)
                x = s[x].root;
        s[temp].root = x;
        return x;
}
int main(void)
{
        int t, n, m, i, j, k, cnt;
        scanf("%d", &t);
        while(t--)
        {
                scanf("%d", &n);
                for(i=1; i<=n; i++)
                {
                        scanf("%d%d", &s[i].x, &s[i].y);
                        s[i].root = i;
                }
                cnt = -1;
                for(i=1; i<=n; i++)
                        for(j=i+1; j<=n; j++)
                        {
                                e[++cnt].x = i;
                                e[cnt].y = j;
                                e[cnt].len = (s[i].x - s[j].x) * (s[i].x - s[j].x) +
                                                (s[i].y - s[j].y) * (s[i].y - s[j].y);
                        }
                sort(e, e+cnt+1, cmp);
                scanf("%d", &m);
                int a, b;
                for(i=1; i<=m; i++)
                {
                        scanf("%d%d", &j, &k);
                        a = find_root(j);
                        b = find_root(k);
                        if(a > b)
                                s[a].root = b; 
                         else
                                s[b].root = a;           
                }
                int top = -1;
                for(i=0; i<=cnt; i++)
                {
                        a = find_root(e[i].x);
                        b = find_root(e[i].y);
                        if( a != b )
                        {
                                if(a > b)
                                         s[a].root = b; 
                                 else
                                         s[b].root = a; 
                                e[++top].x = e[i].x;
                                e[top].y = e[i].y;
                        }
                }
                sort(e, e+top+1, cmp2);
                for(i=0; i<=top; i++)
                        printf("%d %d\n", e[i].x, e[i].y);
                if(t)printf("\n");
        }
        return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值