I’m now solving the following problem in virtualjudge, related with Kd-tree.
https://vjudge.net/problem/Aizu-DSL_2_C#google_vignette
By the way, a runtime error occurred in the code I wrote, even though it passed the test case on the local computer.
This program is written by C. And I guess this issue occurs in the createKdTree() method. How do I solve it?
* my code’s part *
typedef struct {
int x, y;
} Point;
typedef struct Node {
int index;
struct Node *left, *right;
} node;
Point points[MAX_N];
int sortedX[MAX_N][2], sortedY[MAX_N][2];
...
node *createNode(int index) {
node *newNode = (node *) malloc(sizeof(node));
if (newNode == NULL) {
fprintf(stderr, "Failed to allocate memory for new node.n");
exit(EXIT_FAILURE);
}
newNode->index = index;
newNode->left = newNode->right = NULL;
return newNode;
}
node *createKdTree(int l, int r, bool byX, bool isfirst) {
if (l > r) return NULL;
if (l == r) return createNode(sortedX[l][0]);
int m = (l + r) / 2;
int slice = m;
node *root;
if (isfirst) {
if (byX) {
while (slice < r-1 && points[sortedX[slice][0]].x == points[sortedX[m][0]].x) slice++;
} else {
while (slice < r-1 && points[sortedY[slice][0]].y == points[sortedY[m][0]].y) slice++;
}
root = createNode(m);
root->left = createKdTree(l, slice-1, !byX, false);
root->right = createKdTree(slice+1, r, !byX, false);
return root;
}
else {
int k = transmit(byX, m);
int i = transmit(byX, slice);
if (byX) {
while (slice < r-1 && points[sortedY[i][0]].x == points[sortedY[k][0]].x) i = transmit(byX, ++slice);
} else {
while (slice < r-1 && points[sortedX[i][0]].y == points[sortedX[k][0]].y) i = transmit(byX, ++slice);
}
root = createNode(k);
root->left = createKdTree(l, slice-1, !byX, false);
root->right = createKdTree(slice+1, r, !byX, false);
return root;
}
New contributor
protaku is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.