现在的位置: 首页 > 综合 > 正文

CF 并查集(或者图) Ice Skating

2012年08月23日 ⁄ 综合 ⁄ 共 905字 ⁄ 字号 评论关闭

就是给你n个点,这些点必须在相同的x或者y轴上。 求最少加多少个点才能满足这个条件。

哎,没想到。其实,相同x,y能走的就连在一块。

这里必须记上一笔,第一题wa了n次就是因为数组开小了。。。

/*
Pro: 0

Sol:

date:
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <set>
#include <vector>
using namespace std;
int n,a,b,x[1111],y[1111],p[1111];
int find(int x) {return x == p[x] ? x : p[x] = find(p[x]);}
int main(){
    scanf("%d",&n);
    for(int i = 1; i <= n; i ++)
        scanf("%d%d",&x[i],&y[i]),p[i] = i;
    int ans=0;
    for(int i = 1; i <= n; i ++){
        for(int j = 1; j <= n; j ++){
            if(x[i] == x[j] || y[i] == y[j]){
                int px = find(i);
                int py = find(j);
                if(px!=py)
                p[px] = py,ans++;
            }
        }
    }
    printf("%d\n",n-1-ans);
	return 0;
}

#include <cstdio>
int n,x[1111],y[1111],vis[1111],ans;
void go(int indx){
    vis[indx] = true;
//    printf("%d\n",indx);
    for(int i = 1; i<= n; i ++)
        if( (x[i] == x[indx] || y[i] == y[indx] )&& !vis[i])
            go(i);
}
int main(){
    scanf("%d",&n);
    for(int i = 1; i <= n; i ++){
        scanf("%d%d",x + i, y + i);
    }
    ans = -1;
    for(int i = 1; i <= n; i ++){
        if(!vis[i]) go(i),ans ++;
    }
    printf("%d\n",ans);
    return 0;
}

抱歉!评论已关闭.