/*
1046. Plane Spotting排序
题目大意:
给出一个长度为N的非负整数序列(所有数不超过200),还有两个整数M和K,求前M个最优的长度不小于K的连续子序列。
连续子序列的优先级如何比较
1、平均值大的序列优于平均值小的
2、条件1相同情况下,长度大的序列优于长度小的
3、条件1和2相同情况下,结束位置靠前的序列优于结束位置靠后的
1≤N≤300,1≤M≤100,1≤K≤300
解题思路:
使用结构体表示一个子序列,重写比较操作"<"。
对所有可能的子序列进行排序。
struct period {
double aver;
int length,ends;
};
bool operator <(const period &a,const period &b){
if (fabs(a.aver-b.aver)>1e-6) return a.aver>b.aver;
if (a.length!=b.length) return a.length>b.length;
return a.ends<b.ends;
}
重点:更加好的循环方法
for (i=0;i<n;i++) {
temp=0;
for (j=i+1;j<n;j++) {
temp+=a[j];
if (j-i+1>=k) {
p[cnt].length=j-i+1;
p[cnt].ends=j+1;
p[cnt].aver=(double)temp/(j-i+1);
cnt++;
}
}
}
sort(p,p+cnt);
*/
#include <iostream>
#include <cstdlib> //system("pause");
#include <algorithm>
using namespace std;
//1.重点:当需要表示关系组合数据时,学会使用结构体
struct period{
int start;
int end;
double aver;
};
//2.重点:学会使用sort函数 (#include <algorithm>)
bool compare(period a, period b)
{
if(a.aver > b.aver)
return 1;
if(a.aver == b.aver && (a.end - a.start > b.end - b.start))
return 1;
if(a.aver == b.aver && (a.end - a.start == b.end - b.start) && (a.end < b.end))
return 1;
return 0;
}
int main(){
int N;
cin >> N;
struct period p[100000];
for(int i=0;i<N;i++){
int qN;
int bestpN;
int minqN;
int plane[300];
cin >> qN >> bestpN >> minqN;
for(int j=0;j<qN;j++){
cin >> plane[j];
}
//3.重点:三次循环,例如:分别是(5、6、、、n)(1-5,2-6,、、、,(n-5)-n)(1到5累加)
int c=0;
for(int sampleqN=minqN;sampleqN<=qN;sampleqN++){
for(int t=0;t+sampleqN<=qN;t++){
double sum=0;
for(int k=t;k-t<sampleqN;k++){
sum = sum+plane[k];
}
p[c].start=t+1;
p[c].end=t+sampleqN;
p[c].aver=sum/sampleqN;
c++;
}
}
//4.重点:学会使用sort函数 (#include <algorithm>)
sort(p,p+c,compare);
cout << "Result for run "<< i+1 << ":" << endl;
for(int k=0; k<bestpN && k<c; k++){
cout << p[k].start << "-" << p[k].end << endl;
}
}
//system("pause");
return 0;
}
1046. Plane Spotting排序
最新推荐文章于 2016-12-05 12:47:13 发布