;compile c -O3
||
#include <stdio.h>
#include <stdlib.h>
static int trap(const int* height, const int n) {
int trapped = 0;
int* buffer = (int*) calloc(n, sizeof(int));
int max_height = -1;
for(int i = 0; i < n; ++i) {
const int x = buffer[i] = height[i];
if (x > max_height) { max_height = x; }
}
for(int h = 0; h < max_height; ++h) {
int first_index = -1;
int last_index = -1;
for(int i = 0; i < n; ++i) { if (buffer[i] > 0) { first_index = i; i=n+1; } }
for(int i = n - 1; i >= 0; --i) { if (buffer[i] > 0) { last_index = i; i=-1; } }
if (first_index == last_index) { h = max_height+1;
} else {
for(int i = first_index; i <= last_index; ++i) { if (buffer[i] == 0) { ++trapped; } }
for(int i = 0; i < n; ++i) { const int x = buffer[i]; if (x > 0) { buffer[i] = (x - 1);} }
}
}
free(buffer);
return trapped;
}
int main()
{
int a0[] = {0,1,0,1,0};
int a1[] = {0,1,0,2,1,0,1,3,2,1,2,1};
int a2[] = {4,2,0,3,2,5};
int a3[] = {0,1,0};
int a4[] = {0,1,0,1};
int x0 = trap(a0,5);
printf("%d\n", x0 == 1);
int x1 = trap(a1,12);
printf("%d\n", x1 == 6);
int x2 = trap(a2,6);
printf("%d\n", x2 == 9);
int x3 = trap(a3,3);
printf("%d\n", x3 == 0);
int x4 = trap(a4,4);
printf("%d\n", x4 == 1);
return 0;
}
||