This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner scn=new Scanner(System.in); | |
int n=scn.nextInt(),arr[]=new int[4]; | |
while(n--!=0){ | |
for(int i=0;i<4;i++) | |
arr[i]=scn.nextInt(); | |
Arrays.sort(arr);//排序 | |
int x=arr[0]*2+arr[1]+arr[2]+arr[3],y=arr[1]*3+arr[0]+arr[3]; | |
System.out.printf("%d\n",x>y?y:x); | |
} | |
} | |
/*題目:[C_SO42-易] 宵夜 JAVA寫法 | |
作者:1010 | |
時間:西元 2017 年 5 月 */ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdlib.h> | |
int compare(const void *arg1, const void *arg2) { | |
return (*(int *)arg1 - *(int *)arg2); | |
} | |
int main(){ | |
int n=0,arr[4],i=0; | |
scanf("%d",&n); | |
while(n--){ | |
for(i=0;i<4;i++) | |
scanf("%d",&arr[i]); | |
qsort((void *)arr, 4, sizeof(int), compare);//排序 | |
int x=arr[0]*2+arr[1]+arr[2]+arr[3],y=arr[1]*3+arr[0]+arr[3]; | |
printf("%d\n",x>y?y:x); | |
} | |
/*題目:[C_SO42-易] 宵夜 C語言寫法 | |
作者:1010 | |
時間:西元 2017 年 5 月 */ | |
} |
這題是考智力測驗= ( 網路搜尋提燈龍過河或是傳教士與食人族過河都是很經典的題目
這題考法也類似,若以很直覺的每次跟最小權重過去勢必不是最佳解,如下圖:
切記前提記得要排序,而且若單純case1下去做也不一定是最佳解
ex:
1 98 99 100
這時要以case2下去做,也就是最直覺方法才是最佳解