| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
内存与时间超限我用归并写的这个题,之前一直TLE,反复修改还是TLE,想不明白了,最后用AC的和TLE的相对比,发现错误出在申请内存上面,我把int* b = new int[r-l+1]写成int* b = new int[10000]则必定超时,真是让我闻所未闻,这是什么原因
可以提交试下:
#include <cstdio>
#include <algorithm>
using namespace std;
__int64 res;
int a[10010];
void Merge(int *a, int l, int r)
{
if(l < r)
{
int c = (l+r)/2;
Merge(a, l, c);
Merge(a, c+1, r);
int i = l, j = c+1, x = 0;
int *b;
b = (int *)malloc(10000*sizeof(int));
while (i <= c && j <= r)
{
if (a[i] <= a[j]) b[x++] = a[i++];
else
{
b[x++] = a[j++];
res += (c-i+1);
}
}
while (i <= c) b[x++] = a[i++];
while (j <= r) b[x++] = a[j++];
for (x = 0, i = l; i <= r; x++, i++) a[i] = b[x];
free(b);
}
}
int main()
{
int n, i, cnt = 1, k;
scanf("%d", &k);
while (k--)
{
scanf("%d", &n);
res = 0;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
Merge(a, 1, n);
printf("Scenario #%d:\n", cnt++);
printf("%d\n\n", res);
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator