QR5. 乘坐公交
描述
从小明家所在公交站出发有n路公交到公司,现给出每路公交的停站数(不包括起点和终点),及每次停的时间(一路车在每个站停的时间相同)和发车的间隔,先假定每辆车同时在相对时间0分开始发车,且所有车在相邻两个站之间的耗时相同,都为5分钟。给定小明起床的相对时间(相对0的分钟数),请计算他最早到达公司的相对时间。
给定每路车的停站数stops,停站时间period,发车间隔interval及公交路数n,出发时间s。请返回最早到达时间。保证公交路数小于等于500,停站数小于等于50。
C++ 解法, 执行用时: 3ms, 内存消耗: 428KB, 提交时间: 2022-06-07
class TakeBuses { public: int chooseLine(vector<int> stops, vector<int> period, vector<int> interval, int n, int s) { int sumt, min_t = 1e7; for(int i = 0; i < n; i++){ sumt = stops[i]*period[i] + (stops[i] + 1)*5; int yushu = s % interval[i]; if(yushu == 0) sumt += s; else sumt += (s + interval[i] - yushu); min_t = min(min_t, sumt); } return min_t; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 436KB, 提交时间: 2021-09-14
class TakeBuses { public: int chooseLine(vector<int> stops, vector<int> period, vector<int> interval, int n, int s) { // write code here int result = 100000 ; for ( int i = 0; i < n; ++ i ) { int cost_time = s % interval[i] ; int wait_time = cost_time == 0 ? 0 : interval[i] - cost_time ; result = min( result, wait_time + ( stops[i] + 1 ) * 5 + period[i] * stops[i] ) ; } return result + s ; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 456KB, 提交时间: 2020-11-01
int fun(int stop,int period,int interval,int s,int n) { int be=0; while(be<s) be+=interval; be=be+5*(stop+1)+stop*period; return be; } class TakeBuses { public: int chooseLine(vector<int> stops, vector<int> period, vector<int> interval, int n, int s) { // write code here vector<int > ans; for(int i=0;i<n;i++) { ans.push_back(fun(stops[i],period[i],interval[i],s,n)); } sort(ans.begin() , ans.end()); return ans[0]; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 540KB, 提交时间: 2021-10-10
class TakeBuses { public: int chooseLine(vector<int> stops, vector<int> period, vector<int> interval, int n, int s) { int time=1000000000; for (int i=0;i<n;i++){ int wait_time=0; if(s%interval[i]==0){ wait_time=0; } else wait_time=interval[i]-s%interval[i]; int tmp=wait_time+(stops[i]+1)*5+stops[i]*period[i]; if(tmp<time) time=tmp; } return (time+s); } };
C++ 解法, 执行用时: 3ms, 内存消耗: 544KB, 提交时间: 2022-03-26
class TakeBuses { public: int chooseLine(vector<int> stops, vector<int> period, vector<int> interval, int n, int s) { int minTime = INT_MAX; for(int i = 0; i < n; i++){ //220326_DXM_如果起床时间和发车时间错开,则有等车时间interval[i] - s % interval[i] int waitTime = s % interval[i] == 0 ? 0 : interval[i] - s % interval[i]; //220326_DXM_乘车时间 + 停站时间 + 起床时间 minTime = min((stops[i] + 1) * 5 + stops[i] * period[i] + waitTime, minTime); } return minTime + s; } };