D. Vanya and Triangles
time limit per test 4 seconds
memory limit per test 512 megabytes
inputstandard input
outputstandard output
Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane.
Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide.
Output
In the first line print an integer — the number of triangles with the non-zero area among the painted points.
Examples
inputCopy
4
0 0
1 1
2 0
2 2
outputCopy
3
inputCopy
3
0 0
1 1
2 0
outputCopy
1
inputCopy
1
1 1
outputCopy
0
Note
Note to the first sample test. There are 3 triangles formed:
(0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).
Note to the second sample test. There is 1 triangle formed:
(0, 0) - (1, 1) - (2, 0).
Note to the third sample test. A single point doesn’t form a single triangle.
思路
总点数n,共线点数m
ans=C(n,3)-ΣC(m,3)
发现一个式子C(n,3) = ΣC(k,2):k∈[2,n-1]
具体看代码
#include<bits/stdc++.h>
#define mp(i,j) make_pair(i,j)
using namespace std;
typedef long long ll;
const int N=2e3+7;
const int Maxsize=4e6+7;
const ll mod=1e9+7;
struct Hash{
size_t operator()(const pair<int,int>& c)const{
int x=(1ll*c.first*mod+c.second)%Maxsize;
return x>0?x:x+Maxsize;
}
};
ll C[N];
unordered_map<pair<int,int>,int,Hash>P;
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
C[0]=C[1]=C[2]=0;
for(int i=3;i<N;++i)C[i]=C[i-1]+(i-1)*(i-2)/2ll;
int n,g;
cin>>n;
ll ans=C[n];
vector<pair<int,int> >p(n);
for(int i=0;i<n;++i)cin>>p[i].first>>p[i].second;
for(int i=0;i<n;++i){
P.clear();
for(int j=i+1;j<n;++j){
int x=p[i].first-p[j].first;
int y=p[i].second-p[j].second;
if(x<0)x=-x,y=-y;
int g=__gcd(abs(x),abs(y));
if(y==0)++P[mp(1,0)];
else if(x==0)++P[mp(0,1)];
else ++P[mp(x/g,y/g)];
}
for(auto i=P.begin();i!=P.end();++i)ans-=1ll*(i->second)*(i->second-1)/2ll;
}
cout<<ans;
return 0;
}