数据结构算法——1026. 皇后问题

题目

在这里插入图片描述
in
3
1 1
1 2
1 3
out
3

in
4
1 3
2 1
3 4
4 2
out
0

思路

穷举法可以,然而会超时

void exhaustion(queen* q, int n)
{
    int count = 0;
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
            if(q[i].x == q[j].x || q[i].y == q[j].y ||
             ( abs(q[i].x - q[j].x) == abs(q[i].y - q[j].y)) )
             count++;
        }
    }
    cout << count << endl;
}

所以开数组记录每行每列每对角的皇后数量
再根据组合数计算即可
注意从上到左是 x+y
上到右是x-y,为了避免越界要+n保证是整数

代码

#include<iostream>
using namespace std;
struct queen{
    int x;
    int y;
};


long long combination_2(long long n)
{
    if(n < 2)
        return 0;
    else
    {
        return n * (n-1) / 2;
    }
}
void statstics(queen *q, int n)
{
    int* row = new int[n + 1];
    int* column = new int[n + 1];
    int * upleft = new int[2 * n + 1];
    int * upright = new int[2 * n + 1];
    for(int i = 0; i < n + 1; i++)
        row[i] = column[i] = 0;
    
    for(int i = 0; i < 2 * n + 1; i++)
        upleft[i] = upright[i] = 0;
    
    
    for(int i = 0; i < n; i++)
    {
        row[q[i].x ]++;
        column[q[i].y ]++;
        upleft[q[i].x  + q[i].y ]++;
        upright[q[i].x - q[i].y + n]++;
    }
    long long count = 0;
    for(int i = 0; i < n + 1; i++)
        count += combination_2(row[i]) + combination_2(column[i]);
    for(int i = 0; i < 2 * n + 1; i++)
        count += combination_2(upright[i]) + combination_2(upleft[i]);
    cout << count << endl;
}

int main()
{
    int n;
    cin >> n;
    queen* q = new queen[n];
    for(int i = 0; i < n ;i++)
        cin >> q[i].x >> q[i].y;
    //exhaustion(q,n);
    statstics(q,n);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值