PAT A1034 Head of a Gang (30 分)

Insert picture description here
I just started to learn graph theory. This is a graph traversal problem. It is still a bit difficult for me to complete it independently. . . I thought about it for a long time, referenced the code in the book, and debugged it for a long time. I hope that I can make progress in the following topics.

#include <cstdio>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>

using namespace std;

int n, k;
int bh = 0;
map<string,int> ntob;
map<int,string> bton;
map<string,int> cishu;
int G[2020][2020] = {
    
    0};
int weight[2020] = {
    
    0};
bool visited[2020] = {
    
    false};

struct Gang{
    
    
	string name;
	int num;
}gang[1010];

bool cmp(Gang g1, Gang g2){
    
    
	return g1.name < g2.name;
}

int change(string s){
    
    
	if(cishu[s] == 0){
    
    
		cishu[s]++;
		ntob[s] = bh++;
		return bh-1;
	}
	return ntob[s];
}

void DFS(int index, int &head, int &sum, int &num){
    
    
	visited[index] = true;
	num++;
	if(weight[index] > weight[head]){
    
    
		head = index;
	}
	for(int i=0; i<bh; i++){
    
    
		if(G[index][i] != 0){
    
    
			sum += G[index][i];
			G[index][i] = G[i][index] = 0;
			if(visited[i] == false){
    
    
				DFS(i, head, sum, num);
			}
		}
	}
}

int main(){
    
    
	scanf("%d %d", &n, &k);
	for(int i=0; i<n; i++){
    
    
		string s1, s2;
		int w;
		cin >> s1 >> s2 >> w;
		int bh1 = change(s1);
		int bh2 = change(s2);
		bton[bh1] = s1;
		bton[bh2] = s2;
		G[bh1][bh2] += w;
		G[bh2][bh1] += w;
		weight[bh1] += w;
		weight[bh2] += w;
	}
	
	int g = 0;
	for(int i=0; i<bh; i++){
    
    
		if(visited[i] == false){
    
    
			int head = i;
			int sum_w = 0;
			int w = weight[i];
			int num = 0;
			DFS(i, head, sum_w, num);
			if(sum_w>k && num>2){
    
    
				gang[g].name = bton[head];
				gang[g].num = num;
				g++;
			}
		}
	}
	
	sort(gang, gang+g, cmp);
	
	printf("%d\n", g);
	for(int i=0; i<g; i++){
    
    
		printf("%s %d\n", gang[i].name.c_str(), gang[i].num);
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45964844/article/details/113700842