GDUT_22级专题三 F - Built?

题目描述:

There are N towns on a plane. The i-th town is located at the coordinates (xi​,yi​). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(∣a−c∣,∣b−d∣) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

  • 2≤N≤105
  • 0≤xi​,yi​≤109
  • All input values are integers.

Input

Input is given from Standard Input in the following format:

N
1x1​ 1y1​
2x2​ 2y2​
:
xN​ yN​

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample 1

InputcopyOutputcopy
3
1 5
3 9
7 8
3

Build a road between Towns 11 and 22, and another between Towns 22 and 33. The total cost is 2+1=32+1=3 yen.

Sample 2

InputcopyOutputcopy
6
8 3
4 9
12 19
18 1
13 5
7 6
8

思路:

这道题用到kruscal算法,先求y轴的距离并排序填入数组中,再求x轴的距离并排序填入上同一个数组中,最后在对数组排序,从小到大联通城市。

代码:

#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
typedef double db;

struct point{
    int x,y,id;
}a[100005];
struct edge{
    int p1,p2,len;
}ans[200005];
int idx[100005];

bool cmpx(point a,point b){
    return a.x<b.x;
}
bool cmpy(point a,point b){
    return a.y<b.y;
}
bool cmplen(edge a,edge b){
    return a.len<b.len;
}
int find(int k){
    if(idx[k]==k) return k;
    idx[k]=find(idx[k]);
    return idx[k];
}

int main() {
	std::ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        idx[i]=i;
    }
    for(int i=1;i<=n;i++){
        cin>>a[i].x>>a[i].y;
        a[i].id=i;
    }
    sort(a+1,a+1+n,cmpx);
    for(int i=1;i<=n-1;i++){
        ans[i].len=a[i+1].x-a[i].x;
        ans[i].p1=a[i].id;
        ans[i].p2=a[i+1].id;
    }
    sort(a+1,a+1+n,cmpy);
    for(int i=1;i<=n-1;i++){
        ans[i+n-1].len=a[i+1].y-a[i].y;
        ans[i+n-1].p1=a[i].id;
        ans[i+n-1].p2=a[i+1].id;
    }
    sort(ans+1,ans+1+2*n-2,cmplen);
//    for(int i=1;i<=2*n-2;i++){
//        cout<<ans[i].len<<' ';
//    }
//    cout<<endl;
    int cnt=0,judge=0;
    for(int i=1;i<=2*n-2+1&&judge<n-1;i++){
        if(find(ans[i].p1)==find(ans[i].p2)) continue;
        else{
            cnt+=ans[i].len;
            judge++;
            idx[find(ans[i].p1)]=find(ans[i].p2);
        }
    }
    cout<<cnt;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值