SRM146_DIV2
来源:互联网 发布:网络推广做什么的 编辑:程序博客网 时间:2024/05/20 05:05
这次的题独立搞出来了前两道,可喜可贺
250
相同的数字加一起,找最大的和,因为是骰子,所以就是长度为6的数组
public class YahtzeeScore{ public int maxPoints(int[] toss){ int[] result = new int[6]; for (int i : toss){ result[i - 1] += i; } int max = 0; for (int i : result){ max = Math.max(i, max); } return max; }}
500
长方体中的小长方体(不包括正方体)个数,找出所有的长宽组合就行~
public class RectangularGrid{ public long countRectangles(int width, int height){ long result = 0; for (int i = 1; i <= width; i++){ for (int j = 1; j <= height; j++){ if ( i == j) continue; result += (width + 1 - i) * (height + 1 - j); } } return result; }}
1000
过河问题,这个题不会,看了别人的两种答案,一种是思考简单但是编程困难的穷举,一种是思考麻烦编程简单的方法
第一种是简单的递归调用吧
import java.util.Arrays;public class BridgeCrossing{ private boolean[] leftSide; private boolean[] rightSide; private int minTime = Integer.MIN_VALUE; private int time = 0; public int minTime(int[] times){ int length = times.length; if (length == 1){ return times[0]; } leftSide = newBooleanArray(length, true); rightSide = newBooleanArray(length, false); goToTheRight(times); return minTime; } private boolean[] newBooleanArray(int length, boolean b){ boolean[] array = new boolean[length]; Arrays.fill(array, b); return array; } private void goToTheRight(int[] times){ for( int i = 0; i < times.length - 1; i++){ if(!leftSide[i]) continue; for (int j = i + 1; j < times.length; j++){ if(!leftSide[j]) continue; // next state leftSide[i] = leftSide[j] = false; rightSide[i] = rightSide[j] = true; int t = Math.max(times[i], times[j]); time += t; goToTheLeft(times); // reset state time -= t; leftSide[i] = leftSide[j] = true; rightSide[i] = rightSide[j] = false; } } } private void goToTheLeft(int[] times){ if(allTrue(rightSide)){ minTime = Math.min(minTime, time); }else{ for( int i = 0; i < times.length; i++){ if(!rightSide[i]) continue; // next state rightSide[i] = false; leftSide[i] = true; time += times[i]; goToTheRight(times); // rest state time -= times[i]; rightSide[i] = true; leftSide[i] = false; } } } private boolean allTrue(boolean[] rightSide){ for(boolean b : rightSide){ if(!b) return false; } return true; }}
第二种,首先如果人数小于等于3就分情况讨论下,大于3则把行动最快的两个作为运送手电的桥梁,每完成一个轮回就会把两个目前最慢的人搬到对面。不停重复直到剩下的人数小于等于3。
import java.util.Arrays;public class BridgeCrossing{ public int minTime(int[] times){ int total = 0, remaining = times.length; Arrays.sort(times); while (remaining > 3){ total += Math.min(times[0] * 2 + times[remaining - 2] + times[remaining - 1], times[0] + times[1] * 2 + times[remaining - 1]); remaining -= 2; } switch (remaining){ case 1: return times[0]; case 2: return total += times[1]; case 3: return total += times[0] + times[1] + times[2]; default: break; } return total; }}
0 0