题目
思路
图的连通图问题,每一个犯罪团伙都是一个连通分量,找出所有的连通分量后再找出满足条件的连通分量,找出其中最大权值的boss输出.
字符串的hash使用一对map解决
代码
#include <iostream>
#include <string>
#include<algorithm>
#include<vector>
#include<stack>
#include<map>
#include<set>
#include<queue>
#include<list>
#include<sstream>
#include<string.h>
#include<math.h>
using namespace std;
#define nmax 20000
#define inf 999999
int num, K;
int w[nmax];
vector<set<int>> graph;
int visited[nmax];
int maxone = -1;
int maxindex = -1;
int countP = 0;
int all_weight = 0;
map<string, int> m;
map<string, int> STOI;
map<int,string> ITOS;
int number = 0;
int HashStr(string s)
{
auto p = STOI.find(s);
if (p == STOI.end()) {
STOI.insert(pair<string,int>(s,number));
ITOS.insert(pair<int, string>(number, s));
return number++;
}
return p->second;
}
string ReturnStr(int num) {
auto p = ITOS.find(num);
return p->second;
}
void DFS(int cur) {
visited[cur] = 1;
if (w[cur] > maxone) {
maxone = w[cur];
maxindex = cur;
}
++countP;
all_weight += w[cur];
for (auto& p : graph[cur]) {
if (visited[p] == 0) {
DFS(p);
}
}
}
int main()
{
cin >> num >> K;
graph.resize(nmax);
string str1, str2;
int weight;
memset(w, 0, sizeof(w));
memset(visited, 0, sizeof(visited));
for (int i = 0; i < num; ++i) {
cin >> str1 >> str2 >> weight;
int n1 = HashStr(str1);
int n2 = HashStr(str2);
w[n1] += weight;
w[n2] += weight;
graph[n1].insert(n2);
graph[n2].insert(n1);
}
for (int i = 0; i < graph.size(); ++i) {
if (!graph[i].empty()) {
if (visited[i] == 0) {
DFS(i);
if (countP > 2 && all_weight / 2 > K)
m.insert(pair<string, int>(ReturnStr(maxindex), countP));
countP = 0;
all_weight = 0;
maxone = -1;
maxindex = -1;
}
}
}
cout << m.size() << endl;
for (auto& p : m) {
cout << p.first << " " << p.second << endl;
}
}