Poj2431 sort dition (sorting + priority queue)

Source: Internet
Author: User

Idea: first sort the gas stations in ascending order.

Add B [I] to the priority queue when passing through a gas station (pre-store the amount of fuel each time it passes through a gas station)

When the fuel tank is empty: 1. If the queue is empty (it can be understood as the pre-storage volume), it cannot reach the next gas station, or reach the destination.

2. Otherwise, the largest element in the queue will be taken out to fuel the car (Greedy idea)

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>using namespace std;int n,l,p;int t[10005];struct Node{    int a,b;    bool operator < (const Node e)const    {        return e.a>a;    }}s[10005];int B[10005];int A[10005];int main(){    //freopen("d:\\test.txt","r",stdin);    cin>>n;    priority_queue<int>q;    for(int i=0;i<n;i++)    {        scanf("%d%d",&t[i],&s[i].b);    }    cin>>l>>p;    for(int i=0;i<n;i++)    {        s[i].a=l-t[i];    }    sort(s,s+n);    for(int i=0;i<n;i++)    {        A[i]=s[i].a;        B[i]=s[i].b;    }    A[n]=l;B[n]=0;    int pos=0,fuil=p,ans=0;    for(int i=0;i<=n;i++)    {        int d=A[i]-pos;        while(fuil<d)        {            if(q.empty()) {cout<<"-1";return 0;}            fuil+=q.top();            q.pop();            ans++;        }        fuil-=d;        pos=A[i];        q.push(B[i]);    }    cout<<ans<<endl;    return 0;}


Poj2431 sort dition (sorting + priority queue)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.