PAT 1004. Counting Leaves (30)(Java一個測試點未通過 and C++)
阿新 • • 發佈:2019-02-17
1004. Counting Leaves (30)
思路:DFSJava程式碼:第五個執行點返回非零,如果有大神能夠幫我找到問題所在,我就給他介紹女朋友!
import java.util.TreeMap; import java.util.Iterator; import java.util.Scanner; public class Main { public static void main(String[] arg){ Scanner sc =new Scanner(System.in); String firstLine =sc.nextLine().trim(); String[] firstLine_arr =firstLine.split(" "); int N =Integer.parseInt(firstLine_arr[0]); int M =Integer.parseInt(firstLine_arr[1]); if(M==0){ System.out.println("1"); return ; } String[] line ; map.clear(); for(int i=0;i<M;i++){ line =sc.nextLine().trim().split(" "); int k =Integer.parseInt(line[1]); String[] arr =new String[k]; for(int j=0;j<k;j++){ arr[j]=line[j+2]; } map.put(line[0], arr); } DFS("01",1); Iterator<Integer> it = result.keySet().iterator(); System.out.print("0 "); StringBuilder sbd =new StringBuilder(); while(it.hasNext()){ int leafCount =result.get(it.next()); sbd.append(leafCount+" "); } System.out.println(sbd.toString().trim()); } public static void dfs(){ } static TreeMap<String,String[]> map =new TreeMap<String,String[]>(); static TreeMap<Integer,Integer> result=new TreeMap<Integer,Integer>(); public static void DFS(String start,int level){ if(map.containsKey(start)){ int leafCount =0; for(String child :map.get(start)){ if(!map.containsKey(child)){ leafCount++; } else{ DFS(child,level+1); } } if(result.containsKey(level)){ int previousTotal =result.get(level); result.put(level, leafCount+previousTotal); } else{ result.put(level, leafCount); } } } }
C++程式碼(全部通過):
http://blog.csdn.net/iaccepted/article/details/21289205