제출 #803209

#제출 시각아이디문제언어결과실행 시간메모리
803209rocketsriKnapsack (NOI18_knapsack)Java
12 / 100
159 ms15208 KiB
import java.util.*;
public class knapsack {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int m=in.nextInt(), n=in.nextInt();
		long[] a = new long[n];
		long[] w = new long[n];
		long[] freq = new long[n];
		
		HashMap<Long, ArrayList<long[]>> pairs = new HashMap<>(); //(weight, {value, frequency})
		for(int i=0; i<n; i++) {
			a[i]=in.nextLong();
			w[i]=in.nextLong();
			freq[i]=in.nextLong();
		}
		
		for(int i=0; i<n; i++) {
			if(pairs.containsKey(w[i])) {
				pairs.get(w[i]).add(new long[] {a[i], freq[i]});
			}
			else {
				pairs.put(w[i], new ArrayList<>(Arrays.asList(new long[] {a[i], freq[i]})));
			}
		}
		
		long[] dp = new long[m+1];
		for(int i=0; i<m+1; i++) {
			dp[i]=-1;
		}
		dp[0]=0;
		
		for(long weight : pairs.keySet()) {
			ArrayList<long[]> curr = pairs.get(weight);
			Collections.sort(curr, new Comparator<long[]>() {
			    public int compare(long[] x, long[] y) {
			    	if(x[0]>y[0]) {
			    		return 1;
			    	}
			    	else if(x[0]<y[0]) {
			    		return -1;
			    	}
			    	else {
			    		return 0;
			    	}
			    }
			});
			Collections.reverse(curr);
		}
		

		
		for(long weight : pairs.keySet()) {
			long sum=0;
			for(long[] j : pairs.get(weight)) {
				sum += j[1];
			}
			for(int i=m; i>=weight; i--) {
				long f = (long)(i/weight);
				if(dp[i-(int)(Math.min(f, sum)*weight)]!=-1) {
					long c = dp[i-(int)(Math.min(f, sum)*weight)];
					for(long[] j : pairs.get(weight)) {
						long fr = j[1], val = j[0];
						if(fr>f) {
							c += f*val;
							f=0;
							break;
						}
						else {
							c += fr*val;
							f -= fr;
						}
					}
					
					dp[i] = Math.max(dp[i], c);
				}
			}

		}
		
		long max=0;
		for(int i=0; i<m+1; i++) {
			max = Math.max(max, dp[i]);
		}
		
		System.out.println(max);
	}

}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...