算法竞赛入门经典 8.3.3巨人与鬼

/*
输入T,测试例子数
输入n,n行数据
每组数据 k x y, k:0为巨人, 1为鬼, x y为坐标
测试数据
3
2
0 1 1
1 2 2
6
0 3 0
1 5 1
0 5 2
0 4 3
1 2 3
1 1 2
6
0 3 0
0 5 1
0 5 2
1 4 3
1 2 3
1 1 2
*/
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int INF = 1<<30;
const int MAX = 20;
struct node{
    int x;
    int y;
    int k;
};
node A[MAX];
int cur_p;
bool cmp(node a, node b)
{
    double ka, kb; //斜率
    int dax = a.x - A[cur_p].x;
    int day = a.y - A[cur_p].y;
    if(dax == 0) ka = INF;
    else ka = 1.0*day/dax;
    int dbx = b.x - A[cur_p].x;
    int dby = b.y - A[cur_p].y;
    if(dbx == 0) kb = INF;
    else kb = 1.0*dby/dbx;
    if(ka*kb < 0) { // 斜率1正1负
        return ka > kb;
    } else {
        return ka < kb;
    }
}

void dfs(int st, int ed)
{
    int n = ed-st;
    if(n==2) {
        printf("%s(%d,%d) match %s(%d,%d)\n", A[st].k==0?"巨人":"鬼", A[st].x, A[st].y,
                A[st+1].k==0?"巨人":"鬼", A[st+1].x, A[st+1].y);
        return;
    }
    int m = st;
    for(int i=st+1; i<ed; i++) {
        if(A[i].y<A[m].y ||
         (A[i].y==A[m].y && A[i].x<A[m].x)) m = i;
    }
    cur_p = ed-1;
    swap(A[m], A[cur_p]);
    sort(A+st, A+cur_p, cmp);
    if(A[st].k != A[cur_p].k) {
        swap(A[st], A[cur_p-1]);
        dfs(cur_p-1, ed);
        dfs(st, cur_p-1);
    } else {
        int c[2] = {0};
        for(int i=st; i<ed; i++) {
            c[A[i].k]++;
            if(c[0] == c[1]) break;
        }
        dfs(st, st+c[0]*2);
        dfs(st+c[0]*2, ed);
    }
}

int main(){
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    int T;
    scanf("%d", &T);
    int n;
    while(T--) {
        scanf("%d", &n);
        for(int i=0; i<n; i++) {
            scanf("%d%d%d", &A[i].k, &A[i].x, &A[i].y);
        }
        dfs(0, n);
        printf("\n");
    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值