sicily--1046. Plane Spotting

優先級隊列參考:http://blog.sina.com.cn/s/blog_5e518b010100kbts.html

1.一直在“比較”上錯了,沒有注意到

/* A period P1 is better than another period P2 if: 
		**the number of planes per quarter in P1 is higher than in P2; 
		**the numbers are equal but P1 is a longer period (more quarters); 
		** the numbers are equal and they are equally long, but period P1 ends earlier.
		*/
2.比較水,用優先級隊列模擬即可

#include<iostream>
#include<queue>//使用優先級隊列
#include<vector>
using namespace std;

struct Node//某段時間
{
	int start;
	int end;
	double avr;//該段時間內平均每個quarter的飛機
};

struct cmp
{
	bool operator()(const Node &n1, const Node &n2)
	{
		/* A period P1 is better than another period P2 if: 
		**the number of planes per quarter in P1 is higher than in P2; 
		**the numbers are equal but P1 is a longer period (more quarters); 
		** the numbers are equal and they are equally long, but period P1 ends earlier.
		*/
		if(n1.avr != n2.avr)
			return n1.avr < n2.avr;//相當於less,大頂堆;   平均飛機數更多
		else if((n1.end - n1.start) != (n2.end - n2.start))
			return (n1.end - n1.start) < (n2.end - n2.start); //相當於greater,小頂堆;  平均飛機數一樣,長度更長
		else	
			return n1.end > n2.end;//平均飛機數一樣,長度一樣,更早的結束
	}
};
int main()
{
	int runNum;
	cin >> runNum;
	for(int i = 1; i <= runNum; i++)
	{
		int quarters;
		cin >> quarters;
		int output;//輸出的period數
		cin >> output;
		int min;//要求的最小quarter數
		cin >> min;

		int *arr = new int[quarters];
		for(int j = 0; j < quarters; j++)
		{
			cin >> arr[j];//每個quarter內的飛機數
		}
		vector<Node> v;
		//遍歷計算
		for(int m = quarters; m >= min; m--)//因爲同等程度下,長的優先
		{
			for(int j = 0; j < quarters; j++)
			{
				/*
				**譬如:quarters = 3, 數組的下標是0,1,2; min = 3
				*/
				if(j + m > quarters)//越界
					break;
				int sum = 0;
				for(int k = 0; k < m; k++)
				{
					sum = sum + arr[j + k];
				}
				Node temp;
				temp.start = j + 1;
				temp.end = j + m;
				temp.avr = (double)sum / m;//平均每個period內的飛機數
				v.push_back(temp);
			}
		}
		priority_queue<Node, vector<Node>, cmp> Q(v.begin(), v.end());
		cout << "Result for run " << i << ":" << endl;
		for(int j = 0; j < output; j++)
		{
			if(Q.empty())
				break;
			else
			{
				Node temp = Q.top();
				Q.pop();
				cout << temp.start << "-" << temp.end << endl;
			}
		}
	}
	return 0;
}


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