题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1842
题目大意:两个城市之间 隔着一条河,因此两岸的车辆 来往需要一个 大轮船 来回运输,已知河上只有一个船,初始状态船在左岸,此时时间为0,船每次最多只能载N 辆车,且船从一边到对岸的时间花费为cost,已知一共有m 辆车,和出现在两岸的时间,规定如果船到达某岸后没有船,则会停在此岸。按出现顺序输出 每辆车到达对岸的时间。
解题思路:用两个队列 分别保存 两岸的车辆的到达时间,维护一个当前时间,然后判断 队列首元素与当前时间的大小关系。
代码如下:
#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
int id,time,ans;
friend bool operator <(node a,node b)//id排序
{
return a.id < b.id;
}
node(int id=0,int time = 0,int ans=-1):id(id),time(time),ans(ans) {}
};
queue <node> Q[2];
vector <node> v;
void init()
{
while(!Q[0].empty()) Q[0].pop();
while(!Q[1].empty()) Q[1].pop();
v.clear();
}
int main()
{
int T,n,cost,m,tp;
char ss[10];
scanf("%d",&T);
while(T--)
{
init();
scanf("%d%d%d",&n,&cost,&m);
for(int i=0;i<m;i++)
{
scanf("%d%ss",&tp,ss);
if(ss[0]=='l') Q[0].push(node(i,tp,-1));
else Q[1].push(node(i,tp,-1));
}
int mov=0,t=0;
while(!Q[mov].empty()||!Q[!mov].empty())//两岸至少有一岸有车出现
{
int cnt=0;
while(!Q[mov].empty()&&Q[mov].front().time<=t&&cnt<n)//判断装车数是否超过n
{
Q[mov].front().ans = t+cost;
v.push_back(Q[mov].front());
Q[mov].pop();
cnt++;
}
if(cnt) {t+=cost;mov=!mov;} //此岸已装车,运到对岸
else
{
if((Q[!mov].empty()||Q[!mov].front().time>Q[mov].front().time)&&!Q[mov].empty())
{t=Q[mov].front().time;} //对岸的车已空 或者 当前岸的车先到
else if(!Q[!mov].empty()&&Q[!mov].front().time<=t)
{t=t+cost;mov=!mov;} //对岸的车非空 且 对岸的车先到
else if(!Q[!mov].empty()&&Q[!mov].front().time>t)
{t=Q[!mov].front().time+cost;mov=!mov;}//船在当岸等对岸的车到,然后去对岸载车
}
}
sort(v.begin(),v.end());
for(int i = 0; i < v.size(); i++)
printf("%d\n",v[i].ans);
if(T) printf("\n");
}
return 0;
}