1. 程式人生 > 其它 >分組統計(表,查詢,邊插入邊排序)

分組統計(表,查詢,邊插入邊排序)

分組統計(表,查詢,邊插入邊排序)


問題描述

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

輸入格式

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

輸出格式

​ 按順序輸出各個樣例的結果。輸出格式參見樣例,按組號從小到大輸出,組內數字也按編號從小到大輸出。

樣例輸入

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}

樣例說明

​ 第一行輸入1,就說明只有一組資料,下面的沒三行代表一組資料,每組資料中
​ 第一行代表數字的個數,如7 有七個數字
​ 第二行 輸入的就是數字了 2 3 3 8 8 2 3
​ 第三行 表示第二行的分組 如 1 上面為 3 表明3 在1的集合中

思路

​ 第一次做這道題的時候我就想這是簡答的一道面向過程的題,所以一上手就開始寫程式碼,發現根本不對

​ 所以我準備靜下心來,安心建模

建模

沒錯,這道題就是一個表的模型

typedef struct{
	int set;
	int count[MAXSIZE];
}Record,table[MAXSIZE];   // 表的話每個就是記錄

流程(虛擬碼)

  1. 輸入n
  2. 輸入n個數字,每當輸入一個數的時候,在order裡找一找有沒有這個數字,如果沒有加入進去
  3. 對order陣列進行排序
  4. 輸入第三行的n個數字
    1. 每當輸入一個數字的時候,在table[].set中找一找有沒有這個數字,沒有的話加進去,位置為j
    2. 然後對於其上頭的數字,在order中找到其對應的位置k,然後table[j].count[k]++
  5. 對table進行排序
  6. 按照格式輸出table

程式碼

#include<iostream>
#include<cstring>
#define MAXSIZE 100
using namespace std;

typedef struct Node{
	int set;
	int count[MAXSIZE];
}Node;

int main(void){
//	freopen("input.txt", "r", stdin);
	int m;
	cin >> m;
	while(m-- > 0){
		int n;
		Node table[MAXSIZE];
		memset(table, 0, sizeof(table));
		cin >> n;
		int num1[n], order[n], ordercnt = 0;
		for(int i = 0; i < n; i++){
			cin >>num1[i];
			int j;
			for(j = 0; j < ordercnt && order[j] != num1[i]; j++);
			if(j == ordercnt)  //說明order裡面沒有這個序列 
				order[ordercnt++] = num1[i];
		}
		
		for(int i = 0; i < ordercnt-1; i++){
			int k = i;
			for(int j = i+1; j < ordercnt; j++)
				if(order[j] < order[k])
					k = j;
			if(k != i){
				int temp = order[k];
				order[k] = order[i];
				order[i] = temp;
			}
		}//給order排序了
		
		int set, setcnt = 0;
		for(int i = 0; i < n; i++){
			cin >> set;
//			cout << set << " ";  //這裡值輸入了第一個 
			int j;
//			for(int j = 0; j < setcnt && set != table[j].set; j++);
			for(j = 0; j < setcnt && set != table[j].set; j++); 
//			printf("%d %d", j, setcnt); 
			if(j == setcnt){
				//如果沒找到
				table[setcnt++].set = set; 
			}// 先找到對應的set 
			// 不管找沒找到,都插進去
			//先找到對應的位置
			int k;
//			for(int k = 0; num1[i] != order[k]; k++);
			for(k = 0; num1[i] != order[k]; k++);
			//找到num[i]對應的位置k
			table[j].count[k]++; 
//			printf("到達這裡");
		} 
		// 再排序
		for(int i = 0; i < setcnt; i++)
//			printf("%d ", table[i].set);
//		cout<<endl;
		for(int i = 0; i < setcnt-1; i++){
			int k = i;
			for(int j = i + 1; j < setcnt; j++)
				if(table[j].set < table[k].set)
					k = j;
			if(k != i){
				Node temp = table[k];
				table[k] = table[i];
				table[i] = temp;
			}
		}
		// 輸出 
		for(int i = 0; i < setcnt; i++){
			printf("%d={",table[i].set); //輸出這個集合
			for(int j = 0; j < ordercnt; j++){
				printf("%d=%d", order[j], table[i].count[j]);
				if(j != ordercnt-1)
					putchar(',');
			}	
			printf("}\n"); 
//			if(i != setcnt-1)
//				putchar('\n');
		} 
		
	}
	
	return 0;
}