一个gang的总通话用时大于k,且人数大于2,gang的head为其中总通话用时最长的人。根据输入求有几个gang,并按字母顺序输出head和人数。
这一题用并查集和图的遍历,比较繁琐,先要求每一个的总通话时长,合并到一个集合后(合并时可以按通话时长选择节点,通话时间长的为被指向的节点),求每一个集合的总通话时长和人数,根据条件判断是否符合条件。
审题不仔细,有一个点错误,后来重新审一遍题,发现head是保证唯一的。
(用时:1:47:36.95)
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<set>
#include<cstdlib>
//#include <bits/stdc++.h>
using namespace std;
map<string,int> nameToIndex;
map<int,string> indexToName;
struct Node {
int toIndex;
int time;
};
vector<int> timeSum;
int findFa(int x,int father[])
{
while(father[x]!=x) {
x=father[x];
}
return x;
}
void unionFa(int a,int b,int father[])
{
int fa = findFa(a,father);
int fb = findFa(b,father);
if(timeSum[fa] > timeSum[fb]) {
father[b] = fa;
father[a] = fa;
} else {
father[a] = fb;
father[b] = fb;
}
}
int main()
{
int n,k;
cin>>n>>k;
timeSum.resize(n*2);
string name1,name2;
vector<Node> timeVec[n*2];
int time;
int length = 0;
int index = 0;
for(int i=0; i<n; i++) {
cin>>name1>>name2>>time;
//将名称与下标对应 下标与名称对应
if(nameToIndex.count(name1)==0) {
nameToIndex[name1]=length;
indexToName[length]=name1;
timeSum[length] = 0;
length++;
}
index = nameToIndex[name1];
if(nameToIndex.count(name2)==0) {
nameToIndex[name2]=length;
indexToName[length]=name2;
timeSum[length] = 0;
length++;
}
Node node;
node.toIndex = nameToIndex[name2];
node.time = time;
timeVec[index].push_back(node);
}
int father[length];
for(int i=0; i<length; i++) {
father[i]=i;
}
//计算每一个的总通话用时
for(int i=0; i<length; i++) {
for(int j=0; j<timeVec[i].size(); j++) {
timeSum[i] += timeVec[i][j].time;
timeSum[timeVec[i][j].toIndex] += timeVec[i][j].time;
}
}
//合并连接的点
for(int i=0; i<length; i++) {
for(int j=0; j<timeVec[i].size(); j++) {
unionFa(i,timeVec[i][j].toIndex,father);
}
}
set<int> gangs[length];
//用于保存每一个gang的总通话用时
map<string,int> saveSumMap;
vector<string> heads;
int vis[length] = {0};
for(int i=0; i<length; i++) {
index = findFa(i,father);
gangs[index].insert(i);
name1 = indexToName[index];
if(saveSumMap.count(name1)==0) {
saveSumMap[name1] = 0;
}
//求总通话用时
for(int j=0; j<timeVec[i].size(); j++) {
saveSumMap[name1] += timeVec[i][j].time;
}
//判断是否符合条件
if(!vis[index]&&saveSumMap[name1]>k&&gangs[index].size()>2) {
heads.push_back(name1);
vis[index] = 1;
}
}
sort(heads.begin(),heads.end());
cout<<heads.size() <<endl;
for(int i=0; i<heads.size(); i++) {
cout<<heads[i]<<" "<<gangs[nameToIndex[heads[i]]].size() <<endl;
}
return 0;
}