题解:就是根据给的代码片改成C++语言
- 第一发超时:把给的代码片中没用的 for 循环去掉
- 第二发runtime error:将数组大小开大一点过了
accode:
#include <stdio.h>
#include <math.h>
using namespace std;
typedef long long ll;
const int maxn = 2e6 + 10;
int a[maxn], key[maxn];
int son[maxn][4];
int tot;
ll BT(int id, int L, int R)
{
int mid;
tot++;
id = tot;
int B, C;
if(L == R)
{
key[id] = a[L];
return tot;
}
else if(R - L == 1)
{
mid = (L + R) / 2;
BT(son[id][0], L, L);
BT(son[id][1], R, R);
}
else
{
B = L + ceil(1.0 * (R - L) / 3) - 1;
C = (B + R) / 2;
BT(son[id][0], L, B);
BT(son[id][1], B+1, C);
BT(son[id][2], C+1, R);
}
}
int main()
{
int T, n;
scanf("%d", &T);
while(T--)
{
tot = 0;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
int root;
BT(root, 1, n);
printf("%d\n", tot);
}
return 0;
}
|