我必须输出非重叠光盘的数量。据说如果至少一个点重叠(它们接触),则两个盘重叠。我使用的重叠条件:
第一个输入是我应该从键盘读取的光盘数量。接下来的n行输入包含三个整数,即x,y坐标和该圆的半径
问题是我的输出不正确,我尝试了各种条件来检查光盘是否重叠,但每次我得到不同的结果。例如,当输入以下数据时,输出为5,当它应为3时。
10
0 0 5
1 7 1
6 0 3
-12 9 10
8 8 6
5 3 4
3 2 2
7 -10 7
3 15 2
-9 -7 7
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int **readDiscs(int n) //reading discs data into array
{
int **discs = (int **) calloc(n, sizeof(int *));
for (int i = 0; i < n; i++)
{
discs[i] = (int *) calloc(3, sizeof(int));
for (int j = 0; j < 3; j++)
scanf("%d", &discs[i][j]);
}
return (discs);
}
int checkOverlap(int **discs, int length)
{
int *overlaps = (int *) calloc(length, sizeof(int));
int k = 0, R1, R2, X1, X2, Y1, Y2;
for (int i = 0; i < length; i++)
for (int j = i + 1; j < length; j++)
{
R1 = discs[i][2];
R2 = discs[j][2];
X1 = discs[i][0];
X2 = discs[j][0];
Y1 = discs[i][1];
Y2 = discs[j][1];
if (sqrt(pow(X2 - X1, 2) + pow(Y2 - Y1, 2)) <= (R1 + R2)) //if the distance is less or equal to radius,
overlaps[i] = 1; //then they overlap or at least touch
}
for (int f = 0; f < length; f++)
if (overlaps[f] == 0)
k++;
free(overlaps);
return (k);
}
int main(int argc, char *argv[])
{
int **discs;
int n;
scanf("%d", &n);
discs = readDiscs(n);
printf("%d\n", checkOverlap(discs, n));
free(discs);
return (0);
}
答案 0 :(得分:4)
您需要通过注意如果i
和j
重叠来修复搜索,则应记录两个磁盘的搜索。因此,当重叠条件为真时,您应该有两个分配。
假设磁盘1和4(总共4个)重叠,但磁盘2和磁盘3都不与任何磁盘重叠。您记录1重叠(4),但您从未记录4重叠1。