排位赛2-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.
题意
在二维网格上有n头牛,他们之间有n对关系,现在需要建造栅栏,建造得栅栏一定要把有联系的牛都围起来,求最小面积的栅栏面积是多少。
解法
先用并查集将所有牛分好类,然后直接求每一个关系圈的牛所需要的栅栏面积即可。
代码:
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <math.h>
using namespace std;
const int maxn=200010;
int n,m,xx,yy,ans,father[maxn],max_x[maxn],min_x[maxn],max_y[maxn],min_y[maxn],x[maxn],y[maxn];
int getfather(int x)
{
if (father[x]!=x)
father[x]=getfather(father[x]);
return father[x];
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%d%d",&x[i],&y[i]);
for (int i=1;i<=n;i++)
{
father[i]=i;
max_x[i]=-1;
min_x[i]=100000010;
max_y[i]=-1;
min_y[i]=100000010;
}
for (int i=1;i<=m;i++)
{
scanf("%d%d",&xx,&yy);
int fax=getfather(xx);
int fay=getfather(yy);
if (fax==fay) continue;
father[fax]=fay;
}
for (int i=1;i<=n;i++)
{
father[i]=getfather(father[i]);
int fa=father[i];
max_x[fa]=max(max_x[fa],x[i]);
min_x[fa]=min(min_x[fa],x[i]);
max_y[fa]=max(max_y[fa],y[i]);
min_y[fa]=min(min_y[fa],y[i]);
}
ans=-1;
for (int i=1;i<=n;i++)
if (father[i]==i)
{
if (ans==-1) ans=(max_x[i]-min_x[i]+max_y[i]-min_y[i])*2; else
ans=min(ans,(max_x[i]-min_x[i]+max_y[i]-min_y[i])*2);
}
printf("%d",ans);
return 0;
}