【问题标题】:Time Limit Exceeded error in C code . How do I overcome it?C 代码中的时间限制超出错误。我该如何克服它?
【发布时间】:2018-05-09 18:34:17
【问题描述】:

我试图将这段代码转换为只使用 goto 的代码,但是当我尝试在在线 IDE 上运行它时,我不断收到时间限制错误,而当我尝试在我的控制台上运行它时却没有'甚至没有反应或打印错误。

这里是原始代码:

void sort (int skip, int ∗A, int length) {
    for (int n = length ; n > 1 ; n−−) {
        int i = 0 ;
        while (true) {
            if (skip == 0 && i < n−1) {
                if (A[i] > A[i +1]) {
                    A[i] = A[i] ^ A[i+1];
                    A[i +1] = A[i +1] ^ A[i] ;
                    A[i] = A[i] ^ A[i+1] ;
                }
            }else
                break ;
            i++;
       }
   }
}

这是转换后的代码:

#include <stdio.h>

void sort(int skip,int *A,int length){
    int n=length;
    int i,temp,temp2;
Lcond:
    if(n<=1) goto Lend;
Lbody:
    i=0;
Lcond_:
    if(skip!=0) goto Lelse;
    temp=n-1;
    if(i>=temp) goto Lelse;
Lbody_:
    temp2=i+1;
    if(A[i]>A[temp2]) goto Lbody__;
    i++;
    goto Lcond_;
Lbody__:
    A[i]=A[i]^A[temp2];
    A[temp2]=A[temp2]^A[i];
    A[i]=A[i]^A[temp2];
    i++;
    goto Lcond_;
Lelse:
    goto Lcond;
Lend:
    return;
}
int main(){
    int skip=0;
    int A[5]={3,5,1,4,2};
    int length=5;
    sort(skip,A,length);
    for (int i=0;i<5;i++){
            printf("%d\t",A[i]);
    }
}

【问题讨论】:

  • 我试图将这段代码转换为只使用 gotos 的代码 - 为什么???
  • 另外,你不应该永远使用异或交换 - 如果编译器不智能它不知道将异或交换替换为使用中间变量的交换.
  • @ChristianGibbons 下摆?
  • @ChristianGibbons 我认为你对 XOR 交换有误解。en.wikipedia.org/wiki/XOR_swap_algorithm
  • 但是,如果尝试将相同的 object 与自身交换,而不是相同的值,则异或交换将失败。使用数组时可能会发生这种情况...

标签: c error-handling goto


【解决方案1】:

程序永远不会结束,因为唯一的goto LendLcond: if(n&lt;=1) goto Lend;中,而n永远不会改变,所以程序一直在无限循环。你需要一个结束条件。

【讨论】:

  • 或者从将原代码转化为新代码的角度来看,for循环的控制语句中的n--并没有转化成任何东西。
  • 哦,我明白了,谢谢!
  • 谢谢,做到了。我还修复了一些其他错误
猜你喜欢
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多