ref:
http://blog.csdn.net/matrix5467/article/details/8641186
涉及:
1:图的邻接表
2:c++中string, cin, cout
3 : 深搜
4:STL中map, vector, 以及相关iterator用法
#include <stdio.h>
#include <string.h>
#include <vector> //使用vector作链表
#include <string> //使用c++的string
#include <map>
#include <iostream>
using namespace std;
map<string, vector<string>> adj; //邻接表adjacent 图的存储方法
map<string ,int> weight; //各个点的权重
map<string, int>visit; //访问情况
map<string, int>res; //Head点名 和 member数量
int count = 0, totalTime = 0;//一个联通图内的点个数,权重之和
string head; //最大权重的点就是Head
void dfs(string name){//能搜到的点加入 count, 点上的权重加入totoalTime
visit[name] = 1;//首先就标记name 访问,否则会死循环
count++;
totalTime += weight[name];
if(weight[name] > weight[head]){//更新head
head = name;
}
for(vector<string>::iterator it = adj[name].begin(); it != adj[name].end(); it++){
if(visit[*it] == 0){//对于vector的iterator, 访问元素通过*it, fuck!
dfs(*it);
}
}
}
int main(){
freopen("in.txt","r",stdin);
int n,k;
scanf("%d%d",&n, &k);
string name1, name2; //string不是String
int time;
for(int i = 0; i < n; i++){
cin>>name1>>name2>>time; //不能用scanf输入string,使用cin需iostream
adj[name1].push_back(name2);
adj[name2].push_back(name1);
weight[name1] += time;//用+=,说明weight创建key=name1时就初始化value = 0了
weight[name2] += time;//输入的时候,就确定各点的权重了
visit[name1] = 0;
visit[name2] = 0;
//test
//cout<<name1<<"--"<<name2<<time;//输出string也不能用printf
}
//遍历邻接表, 就是遍历这个图
for(map<string,vector<string>>::iterator it = adj.begin(); it != adj.end(); it++){//注意iterator的写法
if(visit[it->first] == 0){//对于map的iterator,
//it->first是key,it->second是value,不能通过it.访问,fuck!
count = 0;
totalTime = 0;
head = it->first;//head 初始值,dfs过程中会改变
dfs(it->first);//深搜之后,检查结果是否满足gang条件
if(count > 2 && totalTime > k*2){
res[head] = count;
}
}
}
printf("%d\n",res.size());
for(map<string,int>::iterator it = res.begin(); it != res.end(); it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}