Problem Description
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
x1 y1
x2 y2
:
xN yNOutput
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.
Example
Sample Input 1
3
1 5
3 9
7 8Sample Output 1
3
Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.Sample Input 2
6
8 3
4 9
12 19
18 1
13 5
7 6Sample Output 2
8
题意: 给出 n 个城镇的坐标 (xi,yi),可在坐标为 (a,b)、(c,d) 的城镇间建一条路,其花费为 min(|a−c|,|b−d|),要求所有城镇之间都变为可达的,问最小花费
思路:
首先根据给出的 n 个城镇分别按横纵坐标排序,计算花费,进行添边
然后对所有的边按花费排序,跑 Kruskal 即可
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 200000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
struct Edge{
int x,y;
int dis;
Edge(){}
Edge(int x,int y,int dis):x(x),y(y),dis(dis){}
bool operator <(const Edge &rhs)const{
return dis<rhs.dis;
}
}edge[N];
int tot;
struct Node{
int x,y;
}node[N];
int father[N];
bool cmpX(int a,int b){
return node[a].x<node[b].x;
}
bool cmpY(int a,int b){
return node[a].y<node[b].y;
}
int Find(int x){
if(father[x]!=x)
return father[x]=Find(father[x]);
return x;
}
int n;
int Kruskal(){
for(int i=1;i<=n;i++)
father[i]=i;
int mst=0;
sort(edge+1,edge+1+tot);
for(int i=1;i<=tot;i++){
int x=Find(edge[i].x);
int y=Find(edge[i].y);
if(x!=y){
mst+=edge[i].dis;
father[x]=y;
}
}
return mst;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d%d",&node[i].x,&node[i].y);
for(int i=1;i<=n;i++)
father[i]=i;
sort(father+1,father+1+n,cmpX);
for(int i=1;i<n;i++){
int x=father[i];
int y=father[i+1];
int dis=node[y].x-node[x].x;
edge[++tot]=Edge(x,y,dis);
}
for(int i=1;i<=n;i++)
father[i]=i;
sort(father+1,father+1+n,cmpY);
for(int i=1;i<n;i++){
int x=father[i];
int y=father[i+1];
int dis=node[y].y-node[x].y;
edge[++tot]=Edge(x,y,dis);
}
int mst=Kruskal();
printf("%d\n",mst);
return 0;
}