PAT 1034. Head of a Gang (30)
2014-05-06 13:36 微尘_无名 阅读(254) 评论(0) 编辑 收藏 举报题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1034
此题考查并查集的应用,要熟悉在合并的时候存储信息:
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> #include <cstddef> using namespace std; struct Person { int personalTime; int gangTime;//记录以当前person为根的集合的gang 的总的通话时间 vector<string> members;//记录以当前person为根的集合的gang members string root; Person() { personalTime=0; gangTime=0; root="-1"; } }; map<string,Person> tree;//并查集 map<string,int> gangs;//符合条件的gang string findRoot(string index) { if(tree[index].root=="-1") return index; else { string tmp=findRoot(tree[index].root); tree[index].root=tmp; return tmp; } } string findHead(string root)//找出当前gang中具有最大weight的为gang head { vector<string> members=tree[root].members; string gangHead=root; int maxPersonalTime=tree[root].personalTime; for(vector<string>::iterator iter=members.begin();iter!=members.end();++iter) { if(tree[*iter].personalTime>maxPersonalTime) { gangHead=*iter; maxPersonalTime=tree[*iter].personalTime; } } return gangHead; } int _tmain(int argc, _TCHAR* argv[]) { int N,K; cin>>N>>K; int i; string Name1,Name2,root1,root2; int Time; for(i=0;i<N;++i) { cin>>Name1>>Name2>>Time; if(tree[Name1].members.size()==0) { tree[Name1].members.push_back(Name1); } if(tree[Name2].members.size()==0) { tree[Name2].members.push_back(Name2); } tree[Name1].personalTime+=Time; tree[Name2].personalTime+=Time; root1=findRoot(Name1); root2=findRoot(Name2); if(root1!=root2) { tree[root1].root=root2; tree[root2].gangTime+=Time; tree[root2].gangTime+=tree[root1].gangTime; tree[root2].members.insert(tree[root2].members.end(),tree[root1].members.begin(),tree[root1].members.end()); } else { tree[root2].gangTime+=Time; } } for(map<string,Person>::iterator iter=tree.begin();iter!=tree.end();++iter) { if(iter->second.root=="-1"&&iter->second.members.size()>2&&iter->second.gangTime>K) { string head=findHead(iter->first); gangs[head]=iter->second.members.size(); } } size_t size=gangs.size(); cout<<size<<endl; if(0==size) { return 0; } for(map<string,int>::iterator iter=gangs.begin();iter!=gangs.end();++iter) { cout<<iter->first<<" "<<iter->second<<endl; } return 0; }