我的java代码会超时0.2m左右,不知道还能怎么改减少运行时间

P3397 地毯

User_BDAD @ 2024-03-28 18:57:45

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int a[][] = new int[n + 2][m + 2];
        // 差分
        for (int i = 0; i < m; i++) {
            int x1 = sc.nextInt();
            int y1 = sc.nextInt();
            int x2 = sc.nextInt();
            int y2 = sc.nextInt();

            ++a[x1][y1];
            ++a[x2 + 1][y2 + 1];
            --a[x2 + 1][y1];
            --a[x1][y2 + 1];
        }
        // 前缀求和
        // 输出
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
}

by weak_in_code @ 2024-03-28 19:05:29

洛谷评测机只会多跑0.2s,多半是T飞了。


by yahuac @ 2024-04-08 21:49:19

@User_BDAD java的标准输入输出较慢,建议使用快读快写加速一下

快读模板

class Read {
    StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    public int nextInt() throws Exception {
        st.nextToken();
        return (int) st.nval;
    }
}

by User_BDAD @ 2024-04-10 23:14:14

@yahuac ok我试试


by 190859136kkkk @ 2024-04-11 13:50:21

@User_BDAD 我也是同样的情况,用快读也超0.2秒,你的可以过吗?


by yahuac @ 2024-04-13 19:28:29

@User_BDAD 还可以加个快写

static PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
pw.println();
pw.close();

by 190859136kkkk @ 2024-04-16 13:07:42

我是这样写的,也超时了

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Scanner;

public class Main {
    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static int nextInt() throws Exception{
        in.nextToken();
        return (int)in.nval;

    }
    static int n,m;
    static PrintWriter out = new PrintWriter(System.out);
    public static void main(String[] args)throws Exception {
        int n=nextInt(),m=nextInt();
        int[][] a=new int [n+2][n+2];
        for(int i=0;i<m;i++) {
            int x1=nextInt(),y1=nextInt(),x2=nextInt(),y2=nextInt();
            a[x1][y1]+=1;
            a[x2+1][y2+1]+=1;
            a[x2+1][y1]-=1;
            a[x1][y2+1]-=1;
        }
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=n;j++) {
                a[i][j]+=a[i][j-1]+a[i-1][j]-a[i-1][j-1];
                out.print(a[i][j]+" ");
                out.flush();
            }
            out.println();
            out.flush();
        }
    }

}

|