Superset CodeForces - 97B(分治基础)

题目链接:点击打开链接

题意:

给定一个点集

添加一些点后再把这个点集输出来。

添加完点后使得对于点集内任意2个点都满足下面2条中至少一条

1、在同一水平线上或在同一垂直线上

2、所围成的矩阵里有其他点。(包含边界)

要求的添加的点数尽量少

思路:

平面分治

先把点按x轴排序,然后找到中间的点,做一条直线 x = a[mid].x;

然后把所有点都投影到这条直线上,那么对于左边的点(包括中间的点)就不需要再和右边的(包括中间的点)进行匹配了。


普通输入输出 160ms

#include <stdio.h>
#include <iostream>
#include <set>
#include <queue>
#include <cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int inf = 1e9;
#define N 10005
pii a[N], b[N*20];
int top, n;
void dfs(int l, int r){
    int mid = (l+r)>>1, maxx = a[mid].first;
    for(int i = l; i <= r; i++)
        b[top++] = pii(maxx, a[i].second);
    if(l < mid)
        dfs(l, mid-1);
    if(mid < r)
        dfs(mid+1, r);
}
void input(){
    for(int i = 1; i <= n; i++)
    scanf("%d%d",&a[i].first,&a[i].second);
    sort(a+1, a+1+n);
    /*先按pair的first从小到大排序,如果first相同的话  按照second从小到大排序
    /*for(int i = 1; i <= n; i++)
    printf("%d %d\n",a[i].first,a[i].second);*/
    top = 0;
}
void output(){
    sort(b, b+top);
    top = unique(b, b+top)-b;
    printf("%d\n",top);
    for(int i = 0; i < top; i++)
        printf("%d %d\n",b[i].first,b[i].second);
}
int main(){
    while(~scanf("%d",&n)){
		input();
        dfs(1, n);
        output();
    }
    return 0;
}

快速输入输出,降至60ms

#include <stdio.h>
#include <iostream>
#include <set>
#include <queue>
#include <cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int inf = 1e9;
template <class T>
inline bool rd(T &ret) {
    char c; int sgn;
    if(c=getchar(),c==EOF) return 0;
    while(c!='-'&&(c<'0'||c>'9')) c=getchar();
    sgn=(c=='-')?-1:1;
    ret=(c=='-')?0:(c-'0');
    while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
    ret*=sgn;
    return 1;
}
template <class T>
inline void pt(T x) {
    if (x <0) {
        putchar('-');
        x = -x;
    }
    if(x>9) pt(x/10);
    putchar(x%10+'0');
}
#define N 10005
pii a[N], b[N*20];
int top, n;
void dfs(int l, int r){
    int mid = (l+r)>>1, maxx = a[mid].first;
    for(int i = l; i <= r; i++)
        b[top++] = pii(maxx, a[i].second);
    if(l < mid)
        dfs(l, mid-1);
    if(mid < r)
        dfs(mid+1, r);
}
void input(){
    for(int i = 1; i <= n; i++) rd(a[i].first), rd(a[i].second);
    sort(a+1, a+1+n);
    top = 0;
}
void output(){
    sort(b, b+top);
    top = unique(b, b+top)-b;
    pt(top); putchar('\n');
    for(int i = 0; i < top; i++)
        pt(b[i].first), putchar(' '), pt(b[i].second), putchar('\n');
}
int main(){
    while(rd(n)){
        input();
        dfs(1, n);
        output();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值