Can anyone explain me how to overcome TLE error in Java. I'm getting Time Limit Exceeded in 3 inputs which are taking 100000 test cases as input

huangapple go评论71阅读模式
英文:

Can anyone explain me how to overcome TLE error in Java. I'm getting Time Limit Exceeded in 3 inputs which are taking 100000 test cases as input

问题

以下是您提供的代码的翻译部分:

import java.io.*;

class Solution9 {
    public static void main(String arg[]) throws Exception {
        int tc;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        tc = Integer.parseInt(br.readLine());
        int sno, q, r;
        String type, s = "";
        for (int i = 0; i < tc; i++) {
            sno = Integer.parseInt(br.readLine());
            sno--;
            q = sno / 12;
            r = sno % 12;
            int csno;
            csno = 11 - r;
            csno += q * 12;
            r %= 6;
            if (r == 0 || r == 5)
                type = "WS";
            else if (r == 1 || r == 4)
                type = "MS";
            else
                type = "AS";
            s = s + (csno + 1) + " " + type + "\n";
        }
        System.out.println(s);
    }
}

请注意,上述内容是您提供的Java代码的翻译部分。如果您还有其他需要翻译的内容或问题,请随时提问。

英文:

Can anyone explain me how to overcome TLE error in Java.

So, I implemented a seating arrangement code in which first line of input take test cases and second line of input takes seat number. In output I've to display the facing seat number of my input and seat type WS, AS or MS.

For example:

2 // test cases
18 // seat number
40 // seat number
19 WS // Output
45 AS // Output

Here is my code which I implemented :

import java.io.*;

class Solution9
{
    public static void main(String arg[])throws Exception
    {
    	int tc;
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    tc=Integer.parseInt(br.readLine());
    int sno,q,r;
    String type,s=&quot;&quot;;
    for(int i=0;i&lt;tc;i++)
    {
        sno=Integer.parseInt(br.readLine());
        sno--;
        q=sno/12;
        r=sno%12;
        int csno;
        csno=11-r;
        csno+=q*12;
        r%=6;
        if(r==0 || r==5)
            type=&quot;WS&quot;;
        else if(r==1 || r==4)
        	type=&quot;MS&quot;;
        else
	        type=&quot;AS&quot;;
        s=s+ (csno+1) + &quot; &quot; + type + &quot;\n&quot; ;
	}
    	System.out.println(s);    
    }
}

答案1

得分: 1

如果您在性能分析工具的控制下运行程序,您很可能会注意到在您的代码行附近有大量时间花费在 StringBuilder 活动上。

s=s+ (csno+1) + " " + type + "\n" ;

反复向 String 中添加内容是低效的,因为每次操作都会执行以下步骤:

  • 将现有的字符串 s 复制到一个 StringBuilder 中(所花费的时间与字符串长度成正比),
  • 将其他组件附加到 StringBuilder
  • StringBuilder 内容创建一个新的 String(再次花费的时间与内容的长度成正比)。

由于您实际上对中间字符串并不感兴趣,只关注最终结果,将代码中的

String s="";

替换为

StringBuilder s=new StringBuilder();

以及将

s=s+ (csno+1) + " " + type + "\n" ;

替换为

s.append(csno+1).append(" ").append(type).append("\n");

这样应该会显著提升性能。

由于 Java 中的 String 是不可变的,对 String 进行任何"更改"实际上是在某种程度上创建一个新的 String(并可能忘记旧的)。因此,在准备好最终结果之前最好使用 StringBuilder,因为 StringBuilder 允许在不重复创建新对象的情况下更改其内容。

英文:

If you run your program under control of a profiler tool, you'll most probably notice a huge amount of time spent in StringBuilder activities around your line

s=s+ (csno+1) + &quot; &quot; + type + &quot;\n&quot; ;

Repeatedly adding something to a String is inefficient, as every time it does the following:

  • Copy the existing string s into a StringBuilder (takes time proportional to the ever-increasing length of the string),
  • append the other components to the StringBuilder,
  • create a new String from the StringBuilder contents (again takes time proportional to the ever-increasing length of the contents).

As you aren't really interested in the intermediate Strings, but only in the final result, replace

String s=&quot;&quot;;

with

StringBuilder s=new StringBuilder();

and

s=s+ (csno+1) + &quot; &quot; + type + &quot;\n&quot; ;

with

s.append(csno+1).append(&quot; &quot;).append(type).append(&quot;\n&quot;);

This should give a substantial performance boost.

As Strings in Java are immutable, "changing" anything about a String means to somehow create a new String (and probably forget about the old one). So it's better to use a StringBuilder until you're ready for the final result, because StringBuilders allow changing their contents without repeatedly creating new ones.

答案2

得分: 0

我怀疑你的问题并不在于代码的性能。它可能有改进的空间,但不会有数量级的提升。我怀疑问题在于你的输入文件格式不正确,它声称拥有的行数比实际行数要多。由于第一行指示了要期望多少行,而且你是从System.in流中读取而不是使用文件输入输出,它会等待直到看到它所期望的行数。System.in不会像FileReader一样产生EOF异常,它只会等待。

编辑:哦!等等!我收回之前的说法。你把整个输出收集到一个字符串中,并且在处理完整个输入之前不输出任何内容。想想那个字符串变得多么庞大!你可能已经用光了内存。

另外,Ralf Kleberhoff 完全正确,你在每一行都创建了一个新的字符串(复制整个字符串以便添加内容)。考虑一下在处理最后的 100,000 行时会复制多少内容。

你确实需要在处理过程中实时输出。虽然这样会使得从标准输入手动进行测试变得有些棘手,但你应该克服这一点。从测试文件中进行测试。

英文:

I doubt your problem is the performance of your code. It could be improved but not by an order of magnitude or anything. I suspect the problem is that your input file is improperly formed, where it is saying that it has more lines than it actually has. Since your first line says how many lines to expect and you are streaming from System.in rather than using File io, it will wait until it sees the lines it expects. System.in will not produce an EOF exception the way a FileReader would, it'll just wait.

Edit: Oh! Wait! I take it back. You're collecting the entire output into a single string and not outputting any of it until your entire input is processed. Think how huge that string is getting! You're probably running out of memory.

Also, Ralf Kleberhoff is completely correct that you're making a new string (copying the whole string in order to add to it) for every row. Consider how much is being copied as you're doing the last couple hundred of your 100,000 rows.

You really have to be outputting as you go along. This makes it awkward to test manually from standard in, but you should get over that. Test from test files.

huangapple
  • 本文由 发表于 2020年10月14日 20:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64352938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定