输入包括多行:
第一行为整数N,N大于零小于等于20;
以下N行,每行为一个数组, 每个元素为一个红包的金额,如:
2
1,2
1,3,4
输出包括N行,每行一个数字,为拿到红包的总金额。如:
2
4
代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Hongbao { public static void main(String[] args) {
Scanner in = new Scanner(System.in); int n = Integer.valueOf(in.nextLine());
List<int[]> list = new ArrayList<int[]>(); for(int i = 0; i < n; i++){
String[] temp = in.nextLine().split(","); int[] arr = new int[temp.length]; for(int j = 0; j < temp.length; j++){
arr[j] = Integer.valueOf(temp[j]);
}
list.add(arr);
} for(int[] l : list){ if(l.length%2 == 0){ int ou = 0; int qi = 0; for(int i = 0; i < l.length; i++){ if(i%2 == 0)
ou += l[i]; else qi += l[i];
}
System.out.println(ou >= qi ? ou : qi);
}else{ int ou = 0; int qi = 0; for(int i = 0; i < l.length - 1; i++){ if(i == 0){
ou += (l[0] >= l[l.length - 1]) ? l[0] : l[l.length - 1];
}else{ if(i%2 == 0)
ou += l[i]; else qi += l[i];
}
}
System.out.println(ou >= qi ? ou : qi);
}
}
}
}
代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Duoshu { public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] firstLine = in.nextLine().split(" ");
TreeNode root = new TreeNode(Integer.parseInt(firstLine[0]));
List<int[]> list = new ArrayList<int[]>(); while(in.hasNextLine()){
String[] line = in.nextLine().split(" "); int[] temp = new int[line.length]; for (int i = 0; i < line.length; i++) {
temp[i] = Integer.valueOf(line[i]);
}
list.add(temp);
}
TreeNode temp = null; for (int i = 1; i < firstLine.length; i++) { if(i == 1){
root.firstChild = new TreeNode(Integer.valueOf(firstLine[i]));
temp = root.firstChild;
addChild(temp, list);
} else{
temp.nextBro = new TreeNode(Integer.valueOf(firstLine[i]));
temp = temp.nextBro;
addChild(temp, list);
}
}
temp = root; while(temp != null){
printBro(temp);
temp = temp.firstChild;
}
} public static void printBro(TreeNode node){
TreeNode temp = node;
System.out.print(temp.value + " "); while(temp.nextBro != null){
temp = temp.nextBro;
System.out.print(temp.value + " ");
}
} public static void addChild(TreeNode node,List<int[]> list){ for (int[] l : list) { if(l[0] == node.value){
TreeNode temp = null;
TreeNode tempNode = null; for(int i = 1; i < l.length; i++){ if(i == 1){
node.firstChild = new TreeNode(Integer.valueOf(l[i]));
tempNode = node.firstChild;
addChild(tempNode, list); if(temp != null)
temp.nextBro = node.firstChild;
} else{
tempNode.nextBro = new TreeNode(Integer.valueOf(l[i]));
tempNode = tempNode.nextBro;
addChild(tempNode, list); if(i == l.length - 1)
temp = node.nextBro;
}
}
}
}
} static class TreeNode{ public int value; public TreeNode firstChild; public TreeNode nextBro; public TreeNode(){
} public TreeNode(int value){ this.value = value;
}
}
}