結果

問題 No.50 おもちゃ箱
ユーザー kou6839
提出日時 2014-12-19 16:33:09
言語 Java
(openjdk 23)
結果
AC  
実行時間 407 ms / 5,000 ms
コード長 1,236 bytes
コンパイル時間 2,108 ms
コンパイル使用メモリ 77,752 KB
実行使用メモリ 41,928 KB
最終ジャッジ日時 2024-06-25 20:45:45
合計ジャッジ時間 10,258 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.math.*;
import java.util.*;
 
public class Main {
	static int dfs(int n,int[] omo,int[] hako,int[] use){
		if(n==((1<<omo.length)-1)){
			int ans=0;
			for(int i=0;i<use.length;i++){
				if(use[i]>0) ans++;
			}
			return ans;
		}
		int res=Integer.MAX_VALUE;
		for(int i=0;i<omo.length;i++){
			if((n&1<<i)!=0) continue;
			int doko=-1;
			for(int j=hako.length-1;j>=0;j--){
				if(omo[i]<=hako[j]){
					hako[j]-=omo[i];
					use[j]++;
					doko=j;
					break;
				}else{
					if(j==0) return 100000;
				}
			}
			n += 1<<i;
			res = Math.min(dfs(n,omo,hako,use),res);
			n-=1<<i;
			use[doko]--;
			hako[doko]+=omo[i];
		}
		return res;
	}
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n= sc.nextInt();
        int[] omo = new int[n];
        for(int i=0;i<n;i++){
        	omo[i]=sc.nextInt();
        }
        int m = sc.nextInt();
        int[] hako =new int[m];
        int[] use = new int[m];
        for(int i=0;i<m;i++){
        	hako[i]=sc.nextInt();
        }
        Arrays.sort(hako);
        int s=dfs(0,omo,hako,use);
        if(s==100000){
        	System.out.println(-1);
        	return;
        }
        System.out.println(s);
        
    }
}		
0