竞技编程: "Time exceeded error"

标签 c gcc optimization

问题描述:

Task A. Amount of subtractions

You have an array a length n. There are m queries (li,ri), for each of which it is necessary to find the sum of numbers sub-array [li,ri]

Input data format:

The first line contains two integers n and m (1 ⩽ n, m ⩽ 105) - the number of numbers and queries. The second line contains n integers a1, a2,. . . , an (1 ⩽ ai ⩽ 109) - the numbers of the array. Each of the following m lines contains two integer numbers li and ri (1 ⩽ li ⩽ ri ⩽ n) - the query.

Output data format:

For each request, take a separate line to answer it.

我的解决方案:

#include <stdio.h>

int main(void) {
    long n = 0;
    long m = 0;

    long l = 0;
    long r = 0;

    register long t = 0; // temporary variable, that contains intermediate results

    scanf("%ld%ld", &n, &m);

    long  a[n];
    long  tr[m]; // array, that contains results

    for (register long i = 0; i < n; i++)
        scanf("%ld", &a[i]);

    for (register long i = 0; i < m; i++) {
        scanf("%ld%ld", &l, &r);

        l--;
        r--;

        t = 0;
        if (l != r) {
            for (register long j = l; j <= r; j++)
                t += *(a + j);
        } else t = *(a + l);

        tr[i] = t; 
    }
    for (register long i = 0; i < m; i++)
        printf("%ld\n", tr[i]);


    return 0;
}

我的解决方案仅通过了 11 项测试中的 6 项。其他 5 项始终返回

Time exceeded error

我对竞技性编程还很陌生。 我应该如何优化我的代码以使大O复杂度低于O(n2)? 任何帮助将不胜感激。

最佳答案

计算数组的累加和,并将其存储到另一个数组中,也就是说, Accumulated[i] = 数组中直到第 i 个索引的数字之和。这可以在 O(n) 中计算。

对于查询,答案将为accumulated[r] -cumulated[l]。这是 O(1)

关于竞技编程: "Time exceeded error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432535/

相关文章:

c++ - 获取模板类对象地址导致模板参数全实例化

optimization - z3 的错误结果

java - Java 中的 vector 距离计算 - 优化

显示 jpeg、bmp 或 pcx 文件的 C 程序

c++ - 一次设置多个数组索引?复合文字?

c - 将值分配给数组并将其打印到控制台时遇到麻烦

c - 将十六进制数字映射到连续整数 : GCC's switch works 1. 比我手写的 SSE2 内在函数 cmpeq/movemask/bsf 快 5 倍?

c++ - 使用一个参数调用宏

c - GCC fatal error : quit. h没有这样的文件或目录

c - 在 Linux 上用 gcc 编译的 C 代码执行转换的是什么?