1034. Head of a Gang

用并查集构造gang,只是名字与数字多了一层转化而已

#include<vector>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
const int N=27*27*27;
int a2i(string s){ return (s[0]-'A')*26*26+(s[1]-'A')*26+s[2]-'A';}
string i2a(int k){
  string s;
  for(int i=0;i<3;++i){ s=char(k%26+'A')+s;k/=26;}
  return s;
}

int level[N],pre[N];
void makeset(){ for(int i=0;i<N;++i) level[i]=1,pre[i]=i; }
int findset(int a){
  if(pre[a]!=a) pre[a]=findset(pre[a]);
  return pre[a];
}
void join(int a,int b){
  int x=findset(a),y=findset(b);
  if(x==y)return;
  if(level[x]>level[y]) level[x]+=level[y],pre[y]=x;
  else level[y]+=level[x],pre[x]=y;
}
struct gang{
  int wei ,head,root;
  gang(int a,int b,int c):root(a),head(b),wei(c){}
  bool operator<(const gang&x)const{return head<x.head;}
};
vector<gang>ggg;   int weight[N];
int main(){
  int n,thresh; cin>>n>>thresh; thresh<<=1;
  makeset();
  while(n--){
    string a,b; int x,y,c;
    cin>>a>>b>>c;
    x=a2i(a),y=a2i(b);
    join(x,y);
    weight[x]+=c ,weight[y]+=c;
  }
  for(int i=0;i<N;++i)
    if(weight[i]){
      int rot=findset(i);
      auto it=find_if(ggg.begin(),ggg.end(),[&](gang&x){return x.root==rot;});
      if(it==ggg.end())
	ggg.emplace_back(rot,i,weight[i]);
      else{
	it->wei+=weight[i];
	if(weight[i]>weight[it->head]) it->head=i;
      }
    }//if
  int cnt=count_if(ggg.begin(),ggg.end(),[&](const gang&x){return level[x.root]>2&&x.wei>thresh;});
  if(cnt){
    cout<<cnt<<endl;
    sort(ggg.begin(),ggg.end());
    for(auto &x:ggg)
      if(x.wei>thresh&&level[x.root]>2)
	cout<<i2a(x.head)<<' '<<level[x.root]<<endl;
  }else cout<<'0';

}


你可能感兴趣的:(1034. Head of a Gang)