Cod sursa(job #1415470)

Utilizator shinerainBarbu Mada shinerain Data 4 aprilie 2015 18:03:31
Problema Problema rucsacului Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.64 kb
package knapsack;

import java.io.File ;
import java.io.FileInputStream ;
import java.io.FileOutputStream ;
import java.io.IOException ;
import java.util.Scanner ;

class Knapsack {
	
	public static int max ( int a , int b ){
		if ( a > b )
			return a ;
		return b ;
	}
	
	public static void print_vect ( int[] a ){
		for ( int i = 0 ; i < a.length ; i++ )
			System.out.print(a[i] + " ") ;
		
		System.out.println() ;
	}

	public static void main ( String[] args ) throws IOException {
		// TODO Auto-generated method stub
		FileInputStream fis = new FileInputStream("rucsac.in");
		
		String s = "";
		 int k ;
		// Read till the end of file
	     while((k=fis.read())!=-1)
	               s+= (char)k ;
	     fis.close();
	    
		Scanner scanner = new Scanner(s);
		
	  
		int N = scanner.nextInt() ;
		int G = scanner.nextInt() ;
	
		
		int[] prev_line = new int[G+1] ;
		
		int[] actu_line = new int[G+1] ;
		
		int cw , cp ; // current weight and profit 
		
		for (int j = 0 ; j < N ; j ++ ){
			cw = scanner.nextInt();
			cp = scanner.nextInt();
			
			
			for ( int i = cw ; i <= G ; i ++ ){
				actu_line[i] = max ( cp + prev_line[i-cw] , prev_line[i]);
				
			}
			
			for ( int i = cw ; i <=G ; i++)
				prev_line[i] = actu_line[i] ;
		
		}
		scanner.close();
		
		File file = new File("rucsac.out");
		
		try (FileOutputStream fop = new FileOutputStream(file)) {
			 
			// if file doesn't exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
			
			String result = ""+actu_line[G];
			fop.write(result.getBytes());
			fop.flush();
			fop.close();
		}
		
	}

}