审题:
//停车场最少能停几辆车
//卡车占连续三位,大车占连续2位,小车占连续一位
//1为不能停,0为能停
代码:
只需要注意判断连续性时避免访问越界就可以了。
int MinCarNum(vector& VecData) { int iNumOfCar = 0; int iCount = 0; while(iCount < VecData.size()) { //小车 if (VecData[iCount] == 0) { //大车 if (iCount + 1 < VecData.size() && VecData[iCount + 1] == 0) { //卡车 if (iCount + 2 < VecData.size() && VecData[iCount + 2] == 0) { ++iNumOfCar; iCount += 3; } else { ++iNumOfCar; iCount += 2; } } else { ++iNumOfCar; ++iCount; } } ++iCount; } return iNumOfCar; } void func1() { vector mVec{0,0,0,0,0,0,1,1,0,1,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,0}; cout << MinCarNum(mVec); } int main() { func1(); return 0; }
执行结果正确:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)