貪婪算法題目練習

1.路上的球

Description

 

There are two parallel roads, each containing N and M buckets, respectively. Each bucket may contain some balls. The buckets on both roads are kept in such a way that they are sorted according to the number of balls in them. Geek starts from the end of the road which has the bucket with a lower number of balls(i.e. if buckets are sorted in increasing order, then geek will start from the left side of the road). The geek can change the road only at the point of intersection(which means, buckets with the same number of balls on two roads). Now you need to help Geek to collect the maximum number of balls.

有兩條平行的道路,每條分別包含N個和M個桶。每個桶裏可能有一些球。這兩條路上的桶都是按照桶裏的球數來分類的。Geek從一條路的盡頭開始,這條路的桶裏有較少的球(也就是說,如果桶是按遞增的順序排列的,那麼Geek將從路的左邊開始)。Geek只能在交叉點改變道路(也就是說,兩條道路上的球數相同的桶)。現在你需要幫助Geek收集最多的球數。

Input

 

The first line of input contains T denoting the number of test cases. The first line of each test case contains two integers N and M, denoting the number of buckets on road1 and road2 respectively. 2nd line of each test case contains N integers, number of balls in buckets on the first road. 3rd line of each test case contains M integers, number of balls in buckets on the second road.

Constraints:1<= T <= 1000,1<= N <= 10^3,1<= M <=10^3,0<= A[i],B[i]<=10^6

輸入的第一行包含T,表示測試用例的數量。每個測試用例的第一行包含兩個整數N和M,分別表示road1和road2上的桶數。每個測試用例的第二行包含N個整數,即第一條路上桶中的球數。每個測試用例的第三行包含M個整數,第二條路上桶中的球數

Output

 

For each test case output a single line containing the maximum possible balls that Geek can collect.

Sample Input 1 

1
5 5
1 4 5 6 8
2 3 4 6 9

Sample Output 1

29

ANSWER:

import java.util.Scanner;

public class Main {

    static long collectBalls(int[] a, int[] b, int n, int m) {
        long f = 0, s = 0, res = 0;
        int i = 0, j = 0;
        while (i < n && j < m) {
            if (a[i] < b[j]) {
                f += a[i++];
            } else if (a[i] > b[j]) {
                s += b[j++];
            } else {
                res += Math.max(f, s) + a[i];
                f = 0;
                s = 0;
                ++i;
                ++j;
            }
        }
        while (i < n) {
            f += a[i++];
        }
        while (j < m) {
            s += b[j++];
        }
        res += Math.max(f, s);
        return res;
    }

    // Driver code
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int cases = Integer.parseInt(sc.nextLine());
        while (cases-- > 0) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            int[] b1 = new int[n];
            int[] b2 = new int[m];
            for (int i = 0; i < n; i++) {
                b1[i] = sc.nextInt();
            }
            for (int i = 0; i < m; i++) {
                b2[i] = sc.nextInt();
            }
            System.out.println(collectBalls(b1, b2, n, m));
        }
    }
}

2.格子裏的整數

Description

 

Given a square grid of size n, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.

Note : It is assumed that negative cost cycles do not exist in input matrix.

Input

 

The first line of input will contain number of test cases T. Then T test cases follow . Each test case contains 2 lines. The first line of each test case contains an integer n denoting the size of the grid. Next line of each test contains a single line containing N*N space separated integers depecting cost of respective cell from (0,0) to (n,n).

Constraints:1<=T<=50,1<= n<= 50

Output

 

For each test case output a single integer depecting the minimum cost to reach the destination.

Sample Input 1 

2
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
2
42 93 7 14

Sample Output 1

327
63
import java.util.Scanner;



  public class Main {

    public static int getResult(int n, int[][] matrix) {
        int[][] dp = new int[n][n];
        dp[0][0] = matrix[0][0];
        for (int i = 1; i < n; i++) {
            dp[0][i] = dp[0][i - 1] + matrix[0][i];
        }
        for (int i = 1; i < n; i++) {
            dp[i][0] = dp[i - 1][0] + matrix[i][0];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = matrix[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
            }
        }
        return dp[n - 1][n - 1];

    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int round = Integer.parseInt(scan.nextLine());
        for (int k = 0; k < round; k++) {
            int n = Integer.parseInt(scan.nextLine());
            String line = scan.nextLine();
            String[] lineStr = line.split(" ");
            int[][] matrix = new int[n][n];
            int index = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(lineStr[index++]);
            }
            System.out.println(getResult(n, matrix));

        }
    }
}

3.時間分隔

Description

 

Given arrival and departure times of all trains that reach a railway station. Your task is to find the minimum number of platforms required for the railway station so that no train waits. 

Note: Consider that all the trains arrive on the same day and leave on the same day. Also, arrival and departure times must not be same for a train.

Input

 

The first line of input contains T, the number of test cases. For each test case, first line will contain an integer N, the number of trains. Next two lines will consist of N space separated time intervals denoting arrival and departure times respectively. 

Note: Time intervals are in the 24-hourformat(hhmm), preceding zeros are insignificant. 200 means 2:00.
Consider the example for better understanding of input.

Constraints:1 <= T <= 100,1 <= N <= 1000,1 <= A[i] < D[i] <= 2359

Output

 

For each test case, print the minimum number of platforms required for the trains to arrive and depart safely.

Sample Input 1 

1
6 
900  940 950  1100 1500 1800
910 1200 1120 1130 1900 2000

Sample Output 1

3
import java.util.Arrays;
import java.util.Scanner;

/**
 * train
 */
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int cases = Integer.parseInt(sc.nextLine());
        while (cases-- > 0) {
            int trains = Integer.parseInt(sc.nextLine());
            int[] arrive = new int[trains];
            int[] leave = new int[trains];
            String[] temp1 = sc.nextLine().split(" ");
            String[] temp2 = sc.nextLine().split(" ");
            for (int i = 0; i < trains; i++) {
                arrive[i] = Integer.parseInt(temp1[i]);
                leave[i] = Integer.parseInt(temp2[i]);
            }
            int result = helper(arrive, leave, trains);
            System.out.println(result);
        }
    }

    public static int helper(int[] arr, int[] dep, int n) {
        // Sort arrival and departure arrays
        Arrays.sort(arr);
        Arrays.sort(dep);

        // plat_needed indicates number of platforms
        // needed at a time
        int plat_needed = 1, result = 1;
        int i = 1, j = 0;

        // Similar to merge in merge sort to process
        // all events in sorted order
        while (i < n && j < n) {
            // If next event in sorted order is arrival,
            // increment count of platforms needed
            if (arr[i] <= dep[j]) {
                plat_needed++;
                i++;

                // Update result if needed
                if (plat_needed > result)
                    result = plat_needed;
            }

            // Else decrement count of platforms needed
            else {
                plat_needed--;
                j++;
            }
        }

        return result;
    }
}

4.硬幣最小數量

Description

 

Given the list of coins of distinct denominations and total amount of money. Output the minimum number of coins required to make up that amount. Output -1 if that money cannot be made up using given coins. You may assume that there are infinite numbers of coins of each type.

Input

 

The first line contains 'T' denoting the number of test cases. Then follows description of test cases. Each cases begins with the two space separated integers 'n' and 'amount' denoting the total number of distinct coins and total amount of money respectively. The second line contains N space-separated integers A1, A2, ..., AN denoting the values of coins. 

Constraints:1<=T<=30,1<=n<=100,1<=Ai<=1000,1<=amount<=100000

Output

 

Print the minimum number of coins required to make up that amount or return -1 if it is impossible to make that amount using given coins.

Sample Input 1 

2
3 11
1 2 5
2 7
2 6

Sample Output 1

3
-1
import java.util.Arrays;
import java.util.Scanner;

/**
 * coin
 */
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int cases = Integer.parseInt(sc.nextLine());
        while (cases-- > 0) {
            String[] temp = sc.nextLine().split(" ");
            int len = Integer.parseInt(temp[0]);
            int amount = Integer.parseInt(temp[1]);
            int[] coins = new int[len];
            String[] tempCoins = sc.nextLine().split(" ");
            for (int i = 0; i < len; i++) {
                coins[i] = Integer.parseInt(tempCoins[i]);
            }
            int result = helper(coins, amount);
            System.out.println(result);
        }
    }

    public static int helper(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            int cost = Integer.MAX_VALUE;
            for (int coin : coins) {
                if (coin <= i) {
                    if (dp[i - coin] != Integer.MAX_VALUE) {
                        cost = Math.min(cost, dp[i - coin] + 1);
                    }
                }
            }
            dp[i] = cost;

        }
        return dp[amount] > amount ? -1 : dp[amount];

    }
}

5.管道網絡

Description

Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outgoing pipe gets a tap. Find the efficient way for the construction of the network of pipes.

在殖民地裏,每家每戶至多有一根管子進出。水箱和水龍頭的安裝方式應確保每個有一個出水管但沒有進水管的房屋屋頂都有水箱,每個只有一個進水管而沒有出水管的房屋屋頂都有水龍頭。爲管網的建設尋找有效途徑。

Input

 

The first line contains an integer T denoting the number of test cases. For each test case, the first line contains two integer n & p denoting the number of houses and number of pipes respectively. Next, p lines contain 3 integer inputs a, b & d, d denoting the diameter of the pipe from the house a to house b.Constraints:1<=T<=50,1<=n<=20,1<=p<=50,1<=a, b<=20,1<=d<=100

Output:

For each test case, the output is the number of pairs of tanks and taps installed i.e n followed by n lines that contain three integers: house number of tank, house number of tap and the minimum diameter of pipe between them.

Sample Input 1 

1
9 6
7 4 98
5 9 72
4 6 10
2 8 22
9 7 17
3 1 66

Sample Output 1

3
2 8 22
3 1 66
5 6 10
import java.util.*;
import java.lang.*;
import java.io.*;

public class Main{

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while(T-->0){
            int n = sc.nextInt();
            int p = sc.nextInt();
            int[] connectedToHouse = new int[n+1];
            int[] connectedFrHouse = new int[n+1];
            int[] connectedPipeDia = new int[n+1];
            for(int i=1;i<=p;i++){
                int x = sc.nextInt();
                int y = sc.nextInt();
                int v = sc.nextInt();
                connectedToHouse[x] = y;
                connectedFrHouse[y] = x;
                connectedPipeDia[x] = v;
            }
            int num=0;
            for(int i=1;i<=n;i++){
                if(connectedFrHouse[i] == 0 && connectedToHouse[i] != 0) num++;
            }
            System.out.println(num);
            for(int i=1;i<=n;i++){
                if(connectedFrHouse[i] != 0 || connectedToHouse[i] == 0) continue;
                int j = i;
                int val = Integer.MAX_VALUE;
                while(connectedToHouse[j]!=0){
                    val = Math.min(val,connectedPipeDia[j]);
                    j = connectedToHouse[j];
                }
                System.out.println(i+" "+j+" "+val);
            }
        }
    }
}

 

6.時間與收益

Description

 

Given a set of n jobs where each job i has a deadline and profit associated to it. Each job takes 1 unit of time to complete and only one job can be scheduled at a time. We earn the profit if and only if the job is completed by its deadline. The task is to find the maximum profit and the number of jobs done.

給定一組n個作業,其中每個作業都有一個截止日期和相關的利潤。每個作業需要1個時間單位才能完成,一次只能安排一個作業。只有工作在截止日期前完成,我們才能獲得利潤。任務是找到最大的利潤和完成的工作的數量。

Input

 

The first line of input contains an integer T denoting the number of test cases.Each test case consist of an integer N denoting the number of jobs and the next line consist of Job id, Deadline and the Profit associated to that Job.

Constraints:1<=T<=100,1<=N<=100,1<=Deadline<=100,1<=Profit<=500

Output

 

Output the number of jobs done and the maximum profit.

Sample Input 1 

2
4
1 4 20 2 1 10 3 1 40 4 1 30
5
1 2 100 2 1 19 3 2 27 4 1 25 5 1 15

Sample Output 1

2 60
2 127
import java.util.*;



public class Main {
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    while (n--!=0) {
      int a=sc.nextInt();
      int arr1[]=new int[a];
      int arr2[]=new int[a];
      int arr3[]=new int[a];
      List<Integer> list=new ArrayList<Integer>();
      for (int i = 0; i < arr3.length; i++) {
        arr1[i]=sc.nextInt();
        arr2[i]=sc.nextInt();
        if (!list.contains(arr2[i])) {
          list.add(arr2[i]);
        }
        
        arr3[i]=sc.nextInt();
      }
      Collections.sort(list);
      int sum=0;
      for (int i = list.size()-1; i >=0; i--) {
        int max=0;
        int temp=-1;
        for (int j = 0; j < arr2.length; j++) {
          if (list.get(i)<=arr2[j]) {
            if (max<arr3[j]) {
              max=arr3[j];
              temp=j;
            }
            //max=Math.max(max, arr3[j]);
          }
        }
        arr3[temp]=-1;
        sum+=max;
      }
      System.out.println(list.size()+" "+sum);
    }
  }
}

 

發佈了27 篇原創文章 · 獲贊 7 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章