codeup 分组统计 (C++)

题目描述

先输入一组数,然后输入其分组,按照分组统计出现次数并输出,参见样例。

输入

输入第一行表示样例数m,对于每个样例,第一行为数的个数n,接下来两行分别有n个数,第一行有n个数,第二行的n个数分别对应上一行每个数的分组,n不超过100。

输出

输出m行,格式参见样例,按从小到大排。

样例输入 Copy

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

样例输出 Copy

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

 思路:使用map<int,int>进行统计即可,之前自己把问题想复杂了(也是没认真的原因。。心思一点都不在学习上。。。)。在输入的过程中进行初始化,将所以分类clas赋值为0,将出现过的数都添加到map中,并将value赋值为0;然后一边输入分组,一边进行统计;最后输出统计好的并且clas != 0 的元素输出。

#include<bits/stdc++.h>
using namespace std;
struct cla{
	int clas;
	map<int,int> num;
};
int main(){
	int m;
	scanf("%d",&m);
	while(m--){
		int n;
		scanf("%d",&n);
		int num[n];
		cla classes[n];   // 分类最多有 n 种 
		for(int i = 0; i < n; i++){
			scanf("%d",&num[i]);
			for(int j = 0; j < n; j++){
				classes[j].clas = 0;
				classes[j].num[num[i]] = 0;   // 初始化 
			}
		}
		map<int,int> c;
		for(int i = 0; i < n; i++){
			int cla; 
			scanf("%d",&cla); 
			classes[cla-1].clas = cla;
			classes[cla-1].num[num[i]]++;
		}
		for(int i = 0; i < n; i++){
			if(classes[i].clas == 0) continue;
			map<int,int> n = classes[i].num;
			printf("%d={",classes[i].clas);
			for(map<int,int>::iterator it = n.begin(); it != n.end(); it++){
				it++;
				if(it != n.end()){
					it--;
					printf("%d=%d,",it->first,it->second);
				}else{
					it--;
					printf("%d=%d}\n",it->first,it->second);
				}
			}
		}
	}
} 
发布了33 篇原创文章 · 获赞 2 · 访问量 1617

猜你喜欢

转载自blog.csdn.net/qq_38969094/article/details/104336045