• A1034 Head of a Gang [图的dfs遍历]


    在这里插入图片描述

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<string>
    #include<math.h>
    #include<algorithm>
    #include<map>
    using namespace std;
    int weight[2001], G[2001][2001];
    bool visit[2001];
    map<int, string>inttoString;
    map<string, int>stringtoInt;
    map<string, int>gang;
    int allnumber = 0, k;
    
    void dfs(int nowi, int& number,int& total,int& head)
    {
    	number++;
    	visit[nowi] = true;
    	if (weight[nowi] > weight[head])
    	{
    		head = nowi;
    	}
    	for (int i = 0; i < allnumber; i++)
    	{
    		if (G[nowi][i] > 0)
    		{
    			total += G[nowi][i];
    			G[nowi][i] = G[i][nowi] = 0;
    			if (visit[i] == false)
    			{
    				dfs(i, number, total, head);
    			}
    		}
    	}
    }
    
    void dfstu()
    {
    	for (int i = 0; i < allnumber; i++)
    	{
    		if (visit[i] == false)
    		{
    			int head = i, number = 0, total = 0;
    			dfs(i, number, total, head);
    			if (number > 2 && total > k)
    			{
    				gang[inttoString[head]] = number;
    			}
    		}
    	}
    }
    
    int change(string str)
    {
    	if (stringtoInt.find(str) != stringtoInt.end())
    	{
    		return stringtoInt[str];
    	}
    	else
    	{
    		stringtoInt[str] = allnumber;
    		inttoString[allnumber] = str;
    		return allnumber++;
    	}
    }
    
    
    
    int main()
    {
    	int w;
    	string str1, str2;
    	int n,m;
    	cin >> n >> k;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> str1 >> str2 >> m;
    		int id1 = change(str1);
    		int id2 = change(str2);
    		weight[id1] += m;
    		weight[id2] += m;
    		G[id1][id2] += m;
    		G[id2][id1] += m;
    	}
    	dfstu();
    	cout << gang.size() << endl;
    	for (auto it = gang.begin(); it != gang.end(); it++)
    	{
    		cout << it->first << " " << it->second << endl;
    	}
    	return 0;
    
    }
    
  • 相关阅读:
    79. Word Search
    97. Interleaving String
    74. Search a 2D Matrix
    73. Set Matrix Zeroes
    72. Edit Distance
    71. Simplify Path
    64. Minimum Path Sum
    shell编程 备份mysql数据库并发送到另一个服务器
    linux 命令执行的判断依据: ;,&&,||
    linux 数据流重定向
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13811999.html
Copyright © 2020-2023  润新知