Codeforces 870E 并查集 解题报告

来源:互联网 发布:诺亚网络萝卜街 编辑:程序博客网 时间:2024/05/16 13:46

Points, Lines and Ready-made Titles

You are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.
You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 109 + 7.

Input

The first line contains single integer n (1 ≤ n ≤ 105) — the number of points.
n lines follow. The (i + 1)-th of these lines contains two integers xi, yi ( - 109 ≤ xi, yi ≤ 109) — coordinates of the i-th point.
It is guaranteed that all points are distinct.

Output

Print the number of possible distinct pictures modulo 109 + 7.

Examples

input
4
1 1
1 2
2 1
2 2
output
16
input
2
-1 -1
0 1
output
9

【解题报告】

代码如下:

#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;#define mod 1000000007#define N 100010int n,f[N],x[N],y[N],t[N<<1];struct Point{int x,y,id;}w[N];bool cmp1(Point a,Point b){return a.x<b.x;}bool cmp2(Point a,Point b){return a.y<b.y;}int find(int i){    return f[i]==i?i:f[i]=find(f[i]);}void unit(int i,int j){    i=find(i);    j=find(j);    if(i==j) y[i]++;    else    {        f[j]=i;        x[i]+=x[j];        y[i]+=y[j]+1;    }}int main(){    scanf("%d",&n);    t[0]=1;    for(int i=1;i<=(n<<1);i++) t[i]=t[i-1]*2%mod;    for(int i=1;i<=n;i++)    {        scanf("%d%d",&w[i].x,&w[i].y);        w[i].id=i;f[i]=i;x[i]=1;    }    sort(w+1,w+n+1,cmp1);    for(int i=2;i<=n;i++) if(w[i].x==w[i-1].x) unit(w[i].id,w[i-1].id);    sort(w+1,w+n+1,cmp2);    for(int i=2;i<=n;i++) if(w[i].y==w[i-1].y) unit(w[i].id,w[i-1].id);    int ans=1;    for(int i=1;i<=n;i++)    {        if(find(i)==i)        {            if(y[i]==x[i]-1) ans=(long long)ans*(t[x[i]+1]-1)%mod;            else ans=(long long)ans*t[x[i]*2-y[i]]%mod;        }    }    printf("%d\n",ans);    return 0;}
原创粉丝点击