首页 > 解决方案 > 如何找到全轮最多的乘客?

问题描述

我是一个新的问题解决者。最近我在codeforces网站上遇到了这个问题。根据用户给出的转弯次数,我设法获得了每个转弯所需的两个值,但我无法找到停止时最多的乘客数量。

#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int(turn);
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=get_on-get_off;
        stops[i]=total_passenger;
    }
    for(int i=0;i<turn;i++){
        if(stops[i]>stops[i+1]){
            highest_total=stops[i];
        }
    }
    cout<<highest_total<<endl;
    return 0;
}

标签: c++

解决方案


您可以尝试使用https://en.cppreference.com/w/cpp/algorithm/max_element 也可以将乘客总数设置为下车和上车之间的差异,我认为您应该添加该差异并分配int* 的内存使用 [] 而不是 ()

#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int[turn];
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger+=get_on-get_off;
        stops[i]=total_passenger;
    }
    cout<<std::max_element(stops, stops + turn)<<endl;
}

推荐阅读