CCF CSP Brush Question Record 35-202006-2 Sparse Vector (Java)

This problem is easy to time out with Java, and the solution is to use BufferedReader for input, use hashmap instead of defining an array, and only define a hashmap.

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
 
class Reader {
    static StringTokenizer token =new StringTokenizer("");
    static BufferedReader reader   =new BufferedReader (new InputStreamReader(System.in)) ;
    static String nextLine() throws IOException {
        return reader.readLine() ;
    }
    static  String next() throws IOException {
        while(!token.hasMoreTokens()) {
            token =new StringTokenizer(reader.readLine()) ;
        }
        return token.nextToken() ;
    }
 
    static int nextInt() throws IOException {
        return Integer.parseInt(next()) ;
    }
    static double nextDouble() throws IOException {
        return Double.parseDouble(next()) ;
    }
 
}

public class 稀疏向量 {

	public static void main(String[] args) throws IOException {
		 
	        int n = Reader.nextInt();
	        int a= Reader.nextInt();
	        int b= Reader.nextInt();
	        long res=0L;
	        /*运行超时了 才30分
	        int[][] v1=new int[2][a];
	        int[][] v2=new int[2][b];
	        for(int i=0;i<a;i++){
	        	v1[0][i]= Reader.nextInt();
	        	v1[1][i]= Reader.nextInt();
	        }
	        for(int i=0;i<b;i++){
	        	v2[0][i]= Reader.nextInt();
	        	v2[1][i]= Reader.nextInt();
	        	for(int j=0;j<a;j++){
	        		if(v1[0][j]==v2[0][i]){
		        		res+=v1[1][j]*v2[1][i];
		        		break;
		        	}
	        	}
	        }
            以下是改进
	      */
	       HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
	       for(int i=0;i<a;i++){
	    	   map.put(Reader.nextInt(), Reader.nextInt());
	       }
	       for(int i=0;i<b;i++){
	    	   int key=Reader.nextInt();
	    	   int value=Reader.nextInt();
	    	   if(map.containsKey(key)){
	    		   res+=value*map.get(key);
	    	   }
	       }
	        System.out.println(res);
	}
}

 

Guess you like

Origin blog.csdn.net/m0_37483148/article/details/108423294