hihocoder-1497-Queen Attack

hihocoder-1497-Queen Attackios

 

#1497 : Queen Attack

時間限制: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.spa

Now given the positions of the queens, find out how many pairs may attack each other?code

輸入

The first line contains an integer N.blog

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.  it

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

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

輸出

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

樣例輸入
5  
1 1  
2 2  
3 3   
1 3
3 1
樣例輸出
10

 

題解:map

  使用unordered_map, 記錄以前添加過的position,由於不可能同時兩個position重疊,兩兩attack的position一定只存在着一種相交方式。

 

 

 

#include <cstdio> 
#include <cstdlib> 

#include <iostream>
#include <unordered_map> 
using namespace std;  

int main()
{
    int n, x, y;
    long long ans = 0; 
    scanf("%d", &n); 
    unordered_map<int, int> hor; 
    unordered_map<int, int> vet; 
    unordered_map<int, int> dx; 
    unordered_map<int, int> vdx; 
    for(int i=0; i<n; ++i)
    {
        scanf("%d %d", &x, &y); 
        if(hor.find(x) != hor.end())
        {
            ans += hor[x]; 
            hor[x] += 1; 
        }else{
            hor[x] = 1; 
        }

        if(vet.find(y) != vet.end())
        {
            ans += vet[y]; 
            vet[y] += 1; 
        }else{
            vet[y] = 1; 
        }

        if(dx.find(x-y) != dx.end())
        {
            ans += dx[x-y]; 
            dx[x-y] += 1; 
        }else{
            dx[x-y] = 1; 
        }

        if(vdx.find(x+y) != vdx.end())
        {
            ans += vdx[x+y]; 
            vdx[x+y] += 1; 
        }else{
            vdx[x+y] = 1; 
        }

    }
    printf("%lld\n", ans );
}
相關文章
相關標籤/搜索