分組統計:map和set的結合使用

題目描述:

先輸入一組數,然後輸入其分組,按照分組統計出現次數並輸出,參見樣例。

輸入描述:

輸入第一行表示樣例數m,對於每個樣例,第一行爲數的個數n,接下來兩行分別有n個數,第一行有n個數,第二行的n個數分別對應上一行每個數的分組,n不超過100。

輸出描述:

輸出m行,格式參見樣例,按從小到大排。

輸入

1
7
3 2 3 8 8 2 3
1 2 3 2 1 3 1

輸出

1={2=0,3=2,8=1}
2={2=1,3=0,8=1}
3={2=1,3=1,8=0}

題目詳情:

https://www.nowcoder.com/practice/5cb47b86911c4aa48722e531a51ec823?tpId=94&tqId=31063&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fbit-kaoyan%2Fquestion-ranking&tPage=2

知識點:

  1. map中出現沒有的鍵。輸出的值對應爲0(不會出現越界的錯誤)
  2. 熟練合理應用 mapset

代碼

#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<map>
#include<set>
using namespace std;

int main()
{
	int sample;
	int num;
	set<int>a;
	set<int>b;
	cin >> sample;
	while (sample--)
	{
		cin >> num;
		int line1[num];
		int line2[num];
		a.clear();
		b.clear();
		int count = 0;
		for (int i = 0; i < num; i++)
		{
			cin >> line1[i];
			a.insert(line1[i]);         // 利用set去掉重複的元素,只統計種類
		}
		for (int j = 0; j < num; j++)
		{
			cin >> line2[j];
			b.insert(line2[j]);			//利用set去掉重複的元素,只統計種類
		}
		map<int, int>totle;
		for (set<int>::iterator it = b.begin(); it != b.end(); it++)
		{
			totle.clear();
			cout << *it << "={";
			for (int i = 0; i < num; i++)
			{
				if (*it == line2[i])
				{
					if (!totle.count(line1[i]))
						totle[line1[i]] = 0;
					totle[line1[i]]++;
				}
			}
			int temp = 0;
			for (set<int>::iterator at = a.begin(); at != a.end(); at++)
			{
				cout << *at << "=" << totle[*at]; 
				temp++;        // map中出現沒有的鍵。輸出的值對應爲0(不會出現越界的錯誤)
				if (temp != a.size())
					cout << ",";
			}
			cout << "}" << endl;
		}


	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章