PAT 1106node
BFS用在tree上,這一個題裏主要關注的是用vector去保存每個節點所鏈接的子節點,當BFS 時,一旦發現該節點下面沒有子節點,這一層必定是最短的路徑,而後用當前的層數去爲後面的節點作判斷,若是接下來,仍然有節點沒有子節點,那麼用層數去驗 證,若是層數一致則是,不然不是。ios
vectorc++
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<vector> 6 #include<queue> 7 #define LL long long; 8 using namespace std; 9 const int MAXN=100005; 10 double pi,r; 11 struct node//節點 12 { 13 int v;//節點編號 14 int cnt;//記錄距離根節點的層數 15 }; 16 vector <int> p[MAXN];//構造這棵樹 17 queue <node> q; 18 int minct=-1; 19 int bfs() 20 { 21 int c=0; 22 bool flag = false; 23 24 while(!q.empty()) 25 { 26 node nd = q.front(); 27 q.pop(); 28 int id = nd.v; 29 int ct = nd.cnt; 30 //初始狀況下flag記爲false,也就是還未有葉子節點 31 //當第一次出現有葉子節點是flag變爲true 32 //若是flag記爲true,那麼後面的節點若是還有子節點也沒有必要再放進去了 33 if(p[id].size()!=0) 34 { 35 if(flag==false) 36 { 37 int len = p[id].size(); 38 for(int i = 0;i<len;i++) 39 { 40 node tn={p[id][i],ct+1};//結構體對象賦值的簡化表達 41 q.push(tn); 42 } 43 } 44 } 45 else 46 { 47 //若是第一次有葉子節點即(flag==false) 48 //或者後面發現葉子節點層數相同(minct==ct) 49 if(flag==false||minct==ct) 50 { 51 flag=true; 52 minct=ct; 53 c++; 54 } 55 } 56 } 57 return c; 58 } 59 int main() 60 { 61 freopen("1106.txt","r",stdin); 62 int m,k,t,s; 63 cin>>m>>pi>>r; 64 for(int i = 0;i<m;i++) 65 { 66 scanf("%d",&k); 67 for(int j = 1;j<=k;j++) 68 { 69 scanf("%d",&t); 70 p[i].push_back(t); 71 } 72 } 73 node nd; 74 nd.v=0; 75 nd.cnt=0; 76 q.push(nd); 77 s = bfs(); 78 for(int i = 1;i<=minct;i++) 79 { 80 pi=pi*(1+r/100.0); 81 } 82 printf("%.4lf %d\n",pi,s); 83 return 0; 84 }