【hiho一下_week255】Queen Attack

本文围绕hihocoder第255周的题目展开,题目是计算无限棋盘上N个皇后中可相互攻击的对数。作者分享自己的解答,因数组过大RE,malloc也不行;还提到别人用map的解答,对map无相应key时的机制存疑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hihocoder的hiho一下,第255周的题目



原题

传送门:https://hihocoder.com/contest/hiho255/problem/1

时间限制:10000ms
单点时限:1000ms
内存限制:256MB


描述
There are N queens in an infinite chessboard. We say two queens may attack each other if they are in the same vertical line, horizontal line or diagonal line even if there are other queens sitting between them.
Now given the positions of the queens, find out how many pairs may attack each other?


输入
The first line contains an integer N.

Then N lines follow. Each line contains 2 integers Ri and Ci indicating there is a queen in the Ri-th row and Ci-th column.

No two queens share the same position.

For 80% of the data, 1 <= N <= 1000

For 100% of the data, 1 <= N <= 100000, 0 <= Ri, Ci <= 1000000000


输出
One integer, the number of pairs may attack each other.

样例输入
5 1 1 2 2 3 3 1 3 3 1
样例输出
10


我的解答

这题感觉很简单,每次读入一个皇后的时候,处理一下,横纵斜坐标,她会和横,纵、斜(x+y相同, 或者x-y相同)上原有的皇后都进行attack。代码如下:

#include <iostream>
#include <memory.h> 

int main(int argc, char** argv) {
	int RSUM[1000000001];
	int CSUM[1000000001];
	int XIE11[1000000001];	// r-c>=0斜对角 
	int XIE12[1000000001];	// r-c<0斜对角
	int XIE2[2000000002];	// r+c斜对角
	memset(RSUM, 0, sizeof(RSUM));
	memset(CSUM, 0, sizeof(CSUM));
	memset(XIE11, 0, sizeof(XIE11));
	memset(XIE12, 0, sizeof(XIE12));
	memset(XIE2, 0, sizeof(XIE2));
	
	int n, r, c;
	double ans = 0;
	scanf("%d", &n);
	while(n--) {
		scanf("%d %d", &r, &c);
		ans = ans + (double)RSUM[r];
		RSUM[r]++;
		ans = ans + (double)CSUM[c];
		CSUM[c]++;
		
		if (r-c >= 0) {
			ans = ans + (double)XIE11[r-c];
			XIE11[r-c]++;
		}
		else {
			ans = ans + (double)XIE12[c-r];
			XIE12[c-r]++;
		}
		ans = ans + (double)XIE2[r+c];
		XIE2[r+c]++;
	}
	printf("%lf\n", ans);
	return 0;
}

但是,不行! 数组开的太大了,RE了,换成malloc也是不行的。


别人的解答

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<map>
using namespace std;
#define ll long long
map<int,int>m1;
map<int,int>m2;
map<int,int>m3;
map<int,int>m4;
int main()
{
    int n,a,b,ans=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d%d",&a,&b);
        ans+=m1[a];
        m1[a]++;
        ans+=m2[b];
        m2[b]++;
        ans+=m3[a+b];
        m3[a+b]++;
        ans+=m4[a-b];
        m4[a-b]++;
    }
    printf("%d\n",ans);
    return 0;
}

map用的真好,受教了。话说map没有相应的key的话,是会直接创建一个pair并调用默认的构造函数??

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值