题目:https://hihocoder.com/problemset/problem/1814
题意:只要任意平行于坐标轴的直线上有2个球,小Hi就可以取走其中一个。
请你计算小Hi最多可以取走几个球?
1.将横坐标相同的点看成集合里面的元素,用并查集建立树,纵坐标同样操作。
2.注意将坐标转为点集
3.找到所有点集的根节点,用所有的点的数目-所有根节点的数目=ans
#include<cstdio>
#include<algorithm>
#define len 1000000
using namespace std;
int use[len];
struct node
{
int x,y,i;
}s[len];
int com1(node a,node b)
{
return a.x<b.x;
}
int com2(node a,node b)
{
return a.y<b.y;
}
int find(int x)
{
return x!=use[x]? use[x]=find(use[x]):x;
}
void unite(node a,node b)
{
int x=find(a.i);
int y=find(b.i);
use[y]=x;
}
int main()
{
int t;
scanf("%d",&t);
for(int i=0;i<=len;i++) use[i]=i;
for(int i=0;i<t;i++)
{
scanf("%d%d",&s[i].x,&s[i].y);
s[i].i=i;
}
int count=0;
sort(s,s+t,com1);
for(int i=0;i<t-1;i++) if(s[i].x==s[i+1].x) unite(s[i],s[i+1]);
sort(s,s+t,com2);
for(int i=0;i<t-1;i++) if(s[i].y==s[i+1].y) unite(s[i],s[i+1]);
for(int i=0;i<t;i++) if(i==find(i)) count++;
printf("%d\n",t-count);
return 0;
}
下面是原创代码
#include <map>
#include <cmath>
#include <ctime>
#include <string>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
struct node {
int x, y, z;
} a[101111];
int n, fa[101111];
bool cmp1(const node &a1, const node &a2) {
return a1.x < a2.x;
}
bool cmp2(const node &a1, const node &a2) {
return a1.y < a2.y;
}
int find(int x) {
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void Union(int x, int y) {
x = find(x), y = find(y);
fa[x] = y;
}
void work() {
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &a[i].x, &a[i].y);
a[i].z = i;
fa[i] = i;
}
sort(a, a + n, cmp1);
for (int i = 0; i < n; ++i) {
if (i && a[i].x == a[i-1].x) {
Union(a[i].z, a[i-1].z);
}
}
sort(a, a + n, cmp2);
for (int i = 0; i < n; ++i) {
if (i && a[i].y == a[i-1].y) {
Union(a[i].z, a[i-1].z);
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (find(i) == i) {
ans++;
}
}
printf("%d\n", n - ans);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int t = clock();
#endif
int TestCase = 1;
// scanf("%d", &TestCase);
while (TestCase --) {
work();
}
#ifndef ONLINE_JUDGE
cerr << "time = " << clock() - t << " ms" << endl;
#endif
return 0;
}