貪心演算法海盜問題java實現
阿新 • • 發佈:2019-02-06
/** * @author dong * */ /** * @author dong * */ import java.util.*; import java.util.Random; public class TestHelloWorld { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++){ a[i] = sc.nextInt(); } haiDao(a); } public static void haiDao(int[] a){ int w=0; int num = 0; Arrays.sort(a); for(int i=0;i<a.length;i++){ if(w<30&& w+a[i]>30){ System.out.println("船上能裝的總數量為" +num+",總重量是"+w); System.out.println("裝上船的商品重量為"); for (int j = 0; j < num; j++) { System.out.print(a[j]+ " "); } return; } w = w+a[i]; num = num+1; } System.out.println("船上能裝的總數量為" +num+",總重量是"+w); } }