Expedition spoj problem

same code I submitted on spoj it show the wrong answer, please resolve it. this is my code

#include
#include
#include
#include
using namespace std;

bool compare(pair<int, int> p1, pair<int,int> p2){
return p1.first > p2.first;
}

int main() {
int n,t,d,f,D,F,prev = 0;
cin>>t;
while(t–){
int ans =0;
int flag=0;
priority_queue pq;
vector<pair<int,int>> v;
cin>>n;
for(int i=0; i<n; i++){
cin>>d>>f;
v.push_back(make_pair(d,f));
}

    sort(v.begin(), v.end(),compare);
    cin>>D>>F;

    for(int i=0; i<n ; i++){
        v[i].first = D - v[i].first;
    }
    prev = 0;
    int x=0;
    while(x<n){
        if(F >= (v[x].first - prev)){
            F = F- (v[x].first - prev);
            pq.push(v[x].second);
            prev = v[x].first;
        }
        else{
            if(pq.empty()){
                flag =1;
                break;
            }
            F += pq.top();
            pq.pop();
            ans++; 
            continue;
        }
        x++;
    }
    if(flag ==1){
        cout<<-1<<endl;
        continue;
    }

    D = D- v[n-1].first;
    if(f >= D){
        cout<<ans<<endl;
        continue;
    }

    while(F < D){
        if(pq.empty()){
            flag =1;
            break;
        }
        F += pq.top();
        pq.pop();
        ans++;
        continue;
    }
    if(flag==1){
        cout<<-1<<endl;
        continue;
    }
    cout<<ans<<endl;

}
return 0;

}

share code in cb ide


for now try to understand this

image

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.