PTA A1056Mice and Rice(25分)

題目:click me~

題意:給出NP只老鼠的質量和它們的初始順序,按每NG只分爲一組,最後剩下的爲一組。對每組老鼠,選出質量最大的1只晉級,晉級的老鼠數就等於該輪分組組數。對這些晉級的老鼠再按上面的方法每NG分爲一組,選出質量最大的一批繼續晉級,這樣到最後只剩下1只老鼠,排名爲1。按照原輸入順序輸出這些排名。

解題思路:

步驟一:開出一個結構體mouse,用以記錄每隻老鼠的質量和排名。定義一個隊列,在算法過程中按順序處理每輪的老鼠。

步驟二:首先算出組數group。

1.用temp記錄當前輪參賽老鼠數(初始爲NP),group記錄當前輪的組數,初始時將老鼠們的編號按順序加入隊列;

2.進入while循環,每一層循環是一輪晉級。

3.每一輪晉級,枚舉當前輪的temp只老鼠,按每NG只老鼠選出組內質量最大的老鼠,將其入隊(晉級),而其他的老鼠排名爲group+1,晉級的老鼠會在下一輪得到新的排名。直到隊列中只剩下1只老鼠,排名記爲1.最後輸出所有老鼠的排名。

code

#include<iostream>
#include<queue>
using namespace std;
const int maxn = 1010;
struct mouse {
	int weight, R;
}mouse[maxn];
int main() {
	int np, ng, order;
	cin >> np >> ng;
	for (int i = 0;i < np;i++)cin >> mouse[i].weight;
	queue<int> q;
	for (int i = 0;i < np;i++) {
		cin >> order;
		q.push(order);
	}
	int temp = np, group;//temp爲當前輪比賽總老鼠數,group爲組數
	while (q.size() != 1) {
		//計算group,當前輪分幾組比賽
		if (temp%ng == 0)group = temp / ng;
		else group = temp / ng + 1;
		//枚舉每一組,選出該組老鼠中質量最大的
		for (int i = 0;i < group;i++) {
			int k = q.front();//k存放該組質量最大的老鼠編號
			for (int j = 0;j < ng;j++) {
				if (i*ng + j >= temp)break;//在最後一組中起作用,及時退出循環
				int front = q.front();//隊首老鼠編號
				if (mouse[front].weight > mouse[k].weight)k = front;//找出質量最大的老鼠
				mouse[front].R = group + 1;//該輪老鼠排名爲group+1
				q.pop();
			}
			q.push(k);//勝利的老鼠晉級
		}
		temp = group;//group只老鼠晉級,下一輪老鼠總數爲group
	}
	mouse[q.front()].R = 1;//隊列中只剩一隻老鼠時,令其排名爲1
	//輸出所有老鼠的信息
	for (int i = 0;i < np;i++) {
		cout << mouse[i].R;
		if (i < np - 1)cout << " ";
	}
	return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

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