PAT甲级1034 DFS求联通分量
作者:互联网
https://pintia.cn/problem-sets/994805342720868352/problems/994805456881434624
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
#include<iostream>
using namespace std;
map<string,int> stoiIndex;
map<int,string> itosIndex;
int numIndex = 1;
int MAP[2005][2005];
int pWeigh[2005];
int visit[2005];
int N,K;
vector<int> totalNum;
vector<int> BOSS;
vector<int> people;
typedef struct
{
string name;
int num;
int pp;
}GANG;
vector<GANG> ans;
int stoiFunc(string s) // 查找字符串的索引值
{
if(stoiIndex[s] == 0)
{
stoiIndex[s] = numIndex;
itosIndex[numIndex] = s;
numIndex++;
return numIndex-1;
}
return stoiIndex[s];
}
int maxW=0,maxP=1;
int total = 0; // 总权值
int totalP = 0; // 总人数
void dfs(int n) // 遍历每个联通分量
{
if(visit[n]) return;
visit[n] = 1;
for(int i = 1;i <= N;i++)
{
// if(visit[i]) continue;
if(MAP[n][i])
{
dfs(i);
total += MAP[n][i]; // 记录总权值
MAP[i][n] = 0;
MAP[n][i] = 0; // 访问过该边后 就将其值置为0
// printf("%d:%d %d\n",n,i,MAP[n][i]);
}
}
if(maxW < pWeigh[n]) // 记录帮派中的BOSS
{
maxW = pWeigh[n];
maxP = n;
}
totalP++;
}
void dfsD()
{
int groupNum = 0;
for(int i = 1;i <= N;i++)
{
if(!visit[i])
{
total = 0,maxW = 0,maxP = 1,totalP = 0;
groupNum++;
dfs(i);
if(totalP > 2 && total > K)
{
GANG t;
t.name = itosIndex[maxP];
t.num = total;
t.pp = totalP;
ans.push_back(t);
}
}
}
}
bool cmp(GANG a,GANG b)
{
return a.name < b.name;
}
void init()
{
for(int i =0 ;i < 2005;i++)
{
for(int j =0 ;j < 2005;j++)
MAP[i][j] = 0;
}
}
int main()
{
cin >> N >> K;
fill(visit,visit+2005,0);
for(int i =0 ;i <N;i++)
{
string A,B;
int time;
cin >> A >> B >> time;
int a = stoiFunc(A);
int b = stoiFunc(B);
MAP[a][b] += time;
MAP[b][a] += time;
pWeigh[a] += time;
pWeigh[b] += time;
}
dfsD();
sort(ans.begin(),ans.end(),cmp);
printf("%d\n",ans.size());
for(int i =0 ;i < ans.size();i++)
{
cout << ans[i].name << " " << ans[i].pp << endl;
// cout << ans[i].num <<endl;
}
return 0;
}
标签:PAT,int,ans,visit,DFS,time,2005,include,1034 来源: https://blog.csdn.net/Alen666/article/details/100560900