【PAT】A1034Head of a Gang
阿新 • • 發佈:2018-10-29
a10 it! temp 圖的遍歷 電話 str 代碼 begin ring
昨天準備學完圖相關的知識,但是學起來挺懵的,理解起來不難,但自己一回想,又什麽都想不起來。
翻來覆去看圖的遍歷,還是覺得有點沒到位。
所以做題來檢測一下,果然學和自己做是兩碼事。
先看的書,又看的柳婼的代碼。思路一樣。
自己照著打了一遍,又自己實現了一遍,總體並不難,關鍵就是三十分的題,要花多點時間讀懂題意。
只發現一個對於我來說的註意事項:
兩個人打電話,可能不止打一次。
#include<string> #include<iostream> #include<map> using namespace std; map<string,int> sti; map<int,string> its; int id=1,K; int G[2010][2010],weight[2010]; bool vis[2010]; int getid(string str){ if(sti[str]==0){ sti[str]=id; its[id]=str; return id++; }else return sti[str]; } void DFS(int u,int &head,int &numMember,int &totalweight){ numMember++; vis[u]=true; if(weight[u]>weight[head]) head=u; for(int j=1;j<id;j++){ if(G[j][u]>0){ totalweight+=G[j][u]; G[j][u]=G[u][j]=0; if(vis[j]==false) DFS(j,head,numMember,totalweight); } } } map<string,int> ans; void DFSTrave(){ for(int i=1;i<id;i++){ if(vis[i]==false){ int head=i,numMember=0,totalweight=0; DFS(i,head,numMember,totalweight); if(numMember>2&&totalweight>K) ans[its[head]]=numMember; } } } int main(){ int N; cin >> N >> K; for(int i=0;i<N;i++){ string str1,str2; int temp; cin >>str1 >> str2 >>temp; int id1=getid(str1); int id2=getid(str2); weight[id1]+=temp; weight[id2]+=temp; G[id1][id2]+=temp;//兩個人不一定只通一次電話 G[id2][id1]+=temp; } DFSTrave(); cout << ans.size() << endl; for(auto it=ans.begin();it!=ans.end();it++) cout << it->first << " " << it->second <<endl; return 0; }
【PAT】A1034Head of a Gang