卡车要经过最少的加油站。
WA几次之后发现要用优先队列。
优先队列之前只对一维数组用过,今晚对结构体用了一下,发现很多易错的地方。
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
struct node
{
int l,f;
friend bool operator< (node n1, node n2)
{
return n1.l<n2.l; //这里确认顺序
}
};
int main()
{
int n,t1,t2,i;
int s[11111];
int sum,over;
scanf("%d",&n);
priority_queue<node> q;
priority_queue<int,vector<int>,less<int> > p;
node tem;
for(int i=1;i<=n;i++)
{scanf("%d%d",&t1,&t2);
tem.l=t1;tem.f=t2;
q.push(tem);
}
scanf("%d%d",&sum,&over);
int k=sum-over,num=0,j=1;
node t=q.top();
if(k>t.l) printf("-1\n");
else
{ int op=0;
while(k>0)
{ // printf("k=%d\n",k);
node tem=q.top();
int flag=1;
if(tem.l<k) flag=0;
while(flag&&!q.empty())
{node tem=q.top();//这里每次都要重新定义 // printf("%d %d %d\n",tem.l,tem.f,k);
p.push(tem.f);
// printf("到p的是%d\n",p.top());
q.pop();
node tem1=q.top();//printf("new %d %d %d\n",tem1.l,tem1.f,k);
if(tem1.l>=k) flag=1;
else flag=0;
}
if(p.empty())
{printf("-1\n"); op=1; break;}
k-=p.top();
// printf("此时最大的%d\n",p.top());
num++;
p.pop();//printf("ok\n");
if(k<=0) break;
}
if(op!=1) printf("%d\n",num);}
}
多练习,多练。