题目连接
http://codeforces.com/contest/651/problem/C
Description
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .
The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Sample Input
3
1 1
7 5
1 5
Sample Output
2
题意
给出n对数,然后让你算出有多少对点的欧几里得距离等于曼哈顿距离
用容斥思想解决,即A∪B = A+B - A∩B,如果给出(x1,y1)与(x2,y2)即先找出同时满足x1-x2==0和y1-y2==0同时成立的,然后x1-x2==0与y1-y2==0单独成立的,代入上式。
代码
#include<bits/stdc++.h>
using namespace std;
std::vector<pair<long,long>>p;
std::vector<pair<long,long>>p1;
int main(int argc, char const *argv[])
{
int n;
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
long long x,y;
scanf("%I64d%I64d",&x,&y);
p.push_back(make_pair(x,y));
p1.push_back(make_pair(y,x));
}
sort(p.begin(),p.end());
sort(p1.begin(),p1.end());
long long ans=0;
long long ant=0;
long long val=0;
for (int i = 0; i < n-1; ++i)
{
if (p[i].first==p[i+1].first&&p[i].second==p[i+1].second)
{
val++;
if (i==n-2)
{
ans+=(val+1)*val/2;
}
}
else{
ans+=(val+1)*val/2;
val=0;
}
}
long long c=0;
for (int i = 0; i < n-1; ++i)
{
if (p[i].first==p[i+1].first)
{
ant++;
if (i==n-2)
{
c+=(ant+1)*ant/2;
}
}
else{
c+=ant*(ant+1)/2;
ant=0;
}
}
long long b=0;
ant=0;
for (int i = 0; i < n-1; ++i)
{
if (p1[i].first==p1[i+1].first)
{
ant++;
if (i==n-2)
{
b+=(ant+1)*ant/2;
}
}
else{
b+=ant*(ant+1)/2;
ant=0;
}
}
printf("%I64d\n",c+b-ans );
return 0;
}
Get
- 熟悉练习了vector,push_back()往后压vector,vector
<pair<x,y>>
p[i]对第i个组对操作。 - 学习了组对pair(x,y),mark_pair(x,y)制成一个组对,sort(p.begin(),p.end()),对按组对的第一个数的大小排序
- p[i].first与p[i].second 组对的第一个与第二个数
- 1 2 3 n=3 有n*(n+) /个组对 …对于这个,以前的处理太蠢了