PAT (Advanced Level) Practice_1034 Head of a Gang (30 分)_字符串型的map构建

  • 题目地址
  • 题目分析:这道题目,考察的内容其实较为繁琐,但是理清思路后,也不见得繁琐了,注释见代码中。
  • 我的代码:
    #include
    #include
    #include
    using namespace std;
    
    int n, k, aa[2001][2001] = { 0 }, weight[2001] = { 0 };//极限情况下2000个不同名配对
    int id = 1, peo = 0, len = 0, headlen = 0, headid;
    bool bb[2001] = { false };
    
    mapstoint;//利用map来构建string和int的一一对应关系
    mapitos;//利用map来构建int和string的一一对应关系
    mapans;
    
    void dfs(int ent) {
    	bb[ent] = true;
    	peo++, len += weight[ent];//将每个节点的所有权重相加 == 2倍的连通分量的所有权重和
    	if (weight[ent] > headlen)
    		headlen = weight[ent], headid = ent;
    	for (int i = 1; i < id; i++)
    		if (bb[i] == false && aa[ent][i])
    			dfs(i);
    }
    
    int main()
    {
    	string s1, s2;
    	scanf("%d %d", &n, &k);
    	for (int i = 0, t; i < n; i++)//建立一一对应关系
    	{
    		cin >> s1 >> s2 >> t;
    		if (stoint[s1] == 0) stoint[s1] = id, itos[id++] = s1;
    		if (stoint[s2] == 0) stoint[s2] = id, itos[id++] = s2;
    		aa[stoint[s1]][stoint[s2]] += t, aa[stoint[s2]][stoint[s1]] += t;
    	}
    	for (int i = 1; i < id; i++)//计算所有节点权重
    		for (int j = 1; j < id; j++)
    			if (j != i && aa[i][j])
    				weight[i] += aa[i][j];
    	int cnt = 0;
    	for (int i = 1; i < id; i++)
    		if (bb[i] == false)
    		{
    			dfs(i);
    			if (peo > 2 && len > 2 * k)//这里的len是每个节点的所有权重和,故k需*2
    			{
    				cnt++;
    				ans[itos[headid]] = peo;
    			}
    			peo = 0, len = 0, headlen = 0;
    		}
    
    	printf("%d\n", cnt);
    	for (auto it = ans.begin(); it != ans.end(); it++)
    		cout << (*it).first << ' ' << (*it).second << endl;
    
    	return 0;
    }

     

你可能感兴趣的:(PAT,(Advanced,Level),Practice)