题意说的是一艘长L的渡轮,初始位置停在河的左岸,负责来回轮渡汽车,只要不超渡轮的长度L,能装多少辆车就装多少辆。河的两岸都有汽车需要摆渡,并且遵循先来后到的原则排成一队等待摆渡。求,要将两岸的所有汽车都摆渡完,渡轮需要渡河多少次。简单题,需要注意的就是,渡轮单趟即算1次,来回是算两次的。
python版本AC代码
testcase = int(input())
while testcase > 0:
testcase -= 1
l,m = map(int,input().split())
l = 100 * l
num_left = num_right = 0
times_left = times_right = 0
L,R = [],[]
for i in range(m):
car,direction = input().split()
car = int(car)
if direction == "left" :
L.append(car)
else:
R.append(car)
num_left = len(L)
sum = 0
i = 0
while i < num_left:
while sum <= l and i < num_left:
sum += L[i]
i += 1
if sum > l:
i -= 1
times_left += 1
sum = 0
num_right = len(R)
sum = 0
i = 0
while i < num_right:
while sum <= l and i < num_right:
sum += R[i]
i += 1
if sum > l:
i -= 1
times_right +=1
sum = 0
if times_left > times_right:
print(times_left*2-1)
else:
print(times_right*2)
C++版本AC代码
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
//#define ZANGFONG
const int maxn = 10010;
int L[maxn],R[maxn];
int main()
{
#ifdef ZANGFONG
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif // ZANGFONG
int Len,num_left, num_right,testcase, m,times_left,times_right;
int i,j,sum;
char d[10];
scanf("%d\n",&testcase);
while(testcase--)
{
memset(L,0,sizeof(L));
memset(R,0,sizeof(R));
memset(d,0,sizeof(d));
num_left = num_right = 0;
times_left = times_right = 0;
scanf("%d%d\n",&Len,&m);
for(i = 0; i < m; i++)
{
scanf("%d %s\n",&j,d);
if(d[0]=='l') L[num_left++] = j;
else R[num_right++] = j;
}
Len = Len * 100;
sum = 0;
for(i = 0; i < num_left; i++)
{
while(sum <= Len && i < num_left) sum += L[i++];
if(sum > Len) i -= 2;
times_left++;
sum = 0;
}
sum = 0;
for(i = 0; i < num_right; i++)
{
while(sum <= Len && i < num_right) sum += R[i++];
if(sum > Len) i-= 2;
times_right++;
sum = 0;
}
if(times_left > times_right) printf("%d\n",times_left*2 - 1);
else printf("%d\n",times_right*2);
}
return 0;
}