百度2015 算法筆試第一題答案

import java.io.BufferedInputStream;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main3 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        int n = 0;// restarant
        int[] m = new int[100];
        int bot = 0;// low
        int top = 0;// high
        int[] c = new int[100];
        int[] v = new int[100];
        int[] enjoy = new int[100];
        while (cin.hasNext()) {
            int T = cin.nextInt();
            enjoy = new int[100];
            for (int i = 0; i < T; i++) {
                n = cin.nextInt();
                bot = cin.nextInt();
                top = cin.nextInt();

                for (int k = 0; k < n; k++) {
                    m[k] = cin.nextInt();
                    for (int j = 0; j < m[k]; j++) {
                        c[j] = cin.nextInt();
                        v[j] = cin.nextInt();
                    }
                    CaluEnjoy(c, v, top, bot, enjoy, 0, m[k]);
                    mark.clear();

                }
                System.out.println(Arrays.toString(enjoy));
                Arrays.sort(enjoy);
                System.out.print(enjoy[enjoy.length - 1] + " ");
            }

        }
    }
    static HashSet<Integer> mark = new HashSet<Integer>();
    private static void CaluEnjoy(int[] c, int[] v, int top, int bot,
            int[] enjoy, int money, int n) {
        // TODO Auto-generated method stub
        for (int i = 0; i < n; i++) {
            if (mark.contains(i)) {
                continue;
            }
            if (money + c[i] > top || i >= n) {
                mark.clear();
                break;
            }
            if (money + c[i] <= top) {
                mark.add(i);
                if ( enjoy[money] + v[i]>enjoy[money + c[i]]) {
                    enjoy[money + c[i]] = enjoy[money] + v[i];
                }
                CaluEnjoy(c, v, top, bot, enjoy, money + c[i], n);
            }
        }

        return;

    }

}

測試數據 :
2
1 4 6
2
6 3 4 5

2 5 10
1
5 10
3
11 100 3 5 2 6

1
1 4 6
2
6 3 4 5

1
2 5 10
1
5 10
3
5 100 3 5 2 6

2
1 4 6
2
5 6 4 5

2 5 10
1
5 10
3
9 12 3 5 2 6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章