栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构算法——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
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);
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/296485.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号