当前位置: 代码迷 >> 综合 >> Fence Planning//并查集//排位2
  详细解决方案

Fence Planning//并查集//排位2

热度:14   发布时间:2024-01-10 06:48:40.0

Fence Planning//并查集


题目

Farmer John’s N cows, conveniently numbered 1…N (2≤N≤105), have a complex social structure revolving around “moo networks” — smaller groups of cows that communicate within their group but not with other groups. Each cow is situated at a distinct (x,y) location on the 2D map of the farm, and we know that M pairs of cows (1≤M<105) moo at each-other. Two cows that moo at each-other belong to the same moo network.

In an effort to update his farm, Farmer John wants to build a rectangular fence, with its edges parallel to the x and y axes. Farmer John wants to make sure that at least one moo network is completely enclosed by the fence (cows on the boundary of the rectangle count as being enclosed). Please help Farmer John determine the smallest possible perimeter of a fence that satisfies this requirement. It is possible for this fence to have zero width or zero height.

Input
The first line of input contains N and M. The next N lines each contain the x and y coordinates of a cow (nonnegative integers of size at most 108). The next M lines each contain two integers a and b describing a moo connection between cows a and b. Every cow has at least one moo connection, and no connection is repeated in the input.

Output
Please print the smallest perimeter of a fence satisfying Farmer John’s requirements.

Example
inputCopy
7 5
0 5
10 5
5 0
5 10
6 7
8 6
8 4
1 2
2 3
3 4
5 6
7 6
outputCopy
10

题意
给坐标,给出哪几个数之间有联系,用矩形框,至少框到一个组。求矩形最小面积

思路

利用并查集分好组,每一个同根的数求各边的最值,求出每一组的面积再比较

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <deque>
#include <queue>
#include <stack>
#define pi 3.1415926
using namespace std;
typedef long long ll;
const ll mod = 1e9+7;
const ll inf=0x3f3f3f3f;
struct dot{
    ll xl=0,yl=0,xs=inf,ys=inf;
}d[200100];
ll n,m;
ll root[200100];
ll x[200100],y[200100];
ll judge[200100]={
    0};
void init(){
    for(ll i=1;i<=n;i++)root[i]=i;return;
}
ll findx(ll p){
    if(root[p]==p) return p;else return root[p]=findx(root[p]);
}
void mergex(ll p,ll q){
    p=findx(p);q=findx(q);if(q==p) return;if(q>p)root[q]=p;else root[p]=q;return;
}
int main(){
    scanf("%lld%lld",&n,&m);init();for(ll i=1;i<=n;i++){
    cin>>x[i]>>y[i];}for(ll i=1;i<=m;i++){
    ll a,b;cin>>a>>b;mergex(a,b);}for(ll i=1;i<=n;i++){
    judge[findx(i)]=1;}for(ll i=1;i<=n;i++){
    ll t=root[i];d[t].xl=max(d[t].xl,x[i]);d[t].yl=max(d[t].yl,y[i]);d[t].xs=min(d[t].xs,x[i]);d[t].ys=min(d[t].ys,y[i]);}ll ans=inf;for(ll i=1;i<=n;i++){
    if(judge[i]==1){
    ll res=d[i].xl-d[i].xs+d[i].yl-d[i].ys;if(res!=0)ans=min(ans,res);}}printf("%lld\n",ans*2);return 0;
}

注意