Problem A. Triangles
Input le: stdin
Output le: stdout
Time limit: 2 seconds
You are given a gure consisting ofnpoints in a 2D-plane and m segments connecting some of them.
We guarantee that any two segments don't share points except their ends and there's no more than one
segment between the same pair of points. Please count the total number of triangles in the given gure.
Input
There're multiple test cases. In each case:
The rst line contains two positive integersnandm. (n200,m20000)
Each of the followingnlines contains two real numbers xi and yi indicating the coordinates of the i-thpoint. ( 100000< xi; yi <100000)
Each of the following m lines contains four real numbers xi, yi, xj, yj. It means (xi; yi) and (xj; yj) are connected by a segment. We guarantee that these points are part of the givennpoints.
Output
For each test case, print a single line contains the total number of triangles in the given gure.
Sample input and output
input
4 5
0 0
1 1
2 0
1 0
0 0 1 1
1 1 2 0
2 0 1 0
1 0 0 0
1 1 1 0
output
3
///
例子 第一个数4 代表有4个点,5代表5个连线,下面4行是输入4个点的坐标,再下面5行是5组连线 比如:(0,0)与(1,1)相连。本题求有多少个三角形。难点就在于,N个点 共线,不好计算三角形的个数。本题可以用F[n][n] 全部赋初值为0,用数字记录点。如果第I个点与第J个点相连,那么f[i][j]和f[j][i]都附上值为1。
/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#define N 222
#define eps 0.00001
using namespace std;
struct point
{
double x;
double y;
}p[N];
int n,m;
double f[N][N];
int okk(int q,int w,int e)
{
return (p[q].y-p[w].y)*(p[w].x-p[e].x)==(p[q].x-p[w].x)*(p[w].y-p[e].y);//判断是否共线
}
int main()
{
while(cin>>n>>m)
{
memset(f,0,sizeof(f));
memset(p,0,sizeof(p));
int i,j,k;
for(i=1;i<=n;i++)
{ double e,g;
cin>>e>>g;
p[i].x=e;
p[i].y=g;
} //记录点
for(i=1;i<=m;i++)
{ double a,b,c,d;
int p1=0,p2=0;
cin>>a>>b>>c>>d;
for(j=1;j<=n;j++)
{
if(fabs(p[j].x-a)<=eps&&fabs(p[j].y-b)<=eps) {p1=j;break;}
}
for(k=1;k<=n;k++)
{
if(fabs(p[k].x-c)<=eps&&fabs(p[k].y-d)<=eps) {p2=k;break;}
}
f[p1][p2]=1;
f[p2][p1]=1;
} //记录连线
for(i=1;i<=n;i++)//下面是记录共线的,如有共线的 记录到数组里面
for(j=1;j<=n;j++)
{
if(f[i][j])
{
for(k=1;k<=n;k++)
if((i!=k)&&(j!=k)&&(f[k][i])&&okk(i,j,k)) {f[k][j]=1;f[j][k]=1;} //代码的最关键的地方 注意只能从i与k有连线,j与i有连线,且三点共线,才能推出j与k相连
}
}
int sum=0;
for(i=1;i<=n;i++)//找三角形 找到了用sum记录
for(j=i+1;j<=n;j++)
if(f[i][j])
{
for(k=j+1;k<=n;k++)
{
if(f[j][k]&&f[i][k]&&(!okk(i,j,k))) {sum++;}//i与j相连 j与k相连 k与i相连 且i,j,k 三点不共线才能构成三角形
}
}
cout<<sum<<endl;
}
return 0;
}