评分网站一直在说我的代码已超过时间限制

时间:2019-02-08 01:17:16

标签: c

好吧,我试图解决问题找牛! [Brian Dean,2012年] 我发现它可以在“ Visual Studio”和其他IDE中很好地工作。但是在“加码”给我的代码打分的网站上……一直说我的代码超出了时间限制... 我的代码有问题吗?

问题是 问题名称:cowfind

输入格式:

  • 第1行:一串长度为N(1 <= N <= 50,000)的括号。

样本输入(文件cowfind.in):

)((()())())

输出格式:

  • 第1行:Bessie可以担任的可能职位数量     排名-即不同的索引对数     x

样本输出(文件cowfind.out):

4

输出详细信息:

贝西有4个可能的位置,如下所示:

1。

)((()())())
 ^^   ^^

2。

)((()())())
  ^^  ^^

3。

)((()())())
  ^^     ^^

4。

)((()())())
 ^^      ^^

代码:

    #include <stdio.h>
    #pragma warning(disable:4996)
    int main() {
        char c[50000];
        int i = 0;
        int j;
        int num = 0;
        while (scanf("%c", &c[i]) == 1)i++;
        c[i] = '\0';
        i = 0;


        while (c[i + 1] != '\0') {
                if ( (c[i] == c[i + 1]) && c[i] == '(') {
                j = i + 2;
                while (c[j + 1] != '\0') {
                    if ((c[j] == c[j + 1]) && c[j] == ')') {
                        num++;
                    }
                    j++;
                }
            }
            i++;
        }

        printf("%d", num);

    }

1 个答案:

答案 0 :(得分:0)

对于许多在线判断问题,关键是想出一种更好的方法来计算结果。他们不仅挑战您编写代码,而且思考如何设计更好的算法。

#include <stdio.h>


int main(void)
{
    long positions = 0; //  Count positions where Bessie may be standing.
    long opens = 0;     //  Count number of times "((" has been seen.
    char previous = 0;  //  Remember previous character.

    //  Loop reading characters.
    while (1)
    {
        //  Get next character.
        int next = getchar();

        //  If there was no next character or the line ended, we are done.
        if (next == EOF || next == '\n') break;

        //  Count the number of times "((" has been seen.
        if (next == '(' && previous == '(')
            ++opens;

        //  When we see "))", add one position for each "((" that precedes it.
        if (next == ')' && previous == ')')
            positions += opens;

        //  Remember the character for the next iteration.
        previous = next;
    }

    //  Show the result.
    printf("%ld\n", positions);
}