1046. Plane Spotting

本文介绍了一种使用C++结构体存储区间数据的方法,并通过sort函数进行排序,以找到最佳区间段。文章详细展示了如何利用三重循环计算平均值,并根据特定条件进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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++;  
            }                  
        }  
        //2.重点:学会使用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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值