题解 | #MP3光标位置#
MP3光标位置
http://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
#include <bits/stdc++.h>
using namespace std;
int main(){
//输入
int musicNum = 0;
string command = "";
cin >> musicNum;
cin >> command;
//处理命令
if(musicNum <= 4){
int curMusicPos = 1; //当前光标的一个位置
for(char ch : command){
if(ch == 'U') curMusicPos--;
else curMusicPos++;
}
//输出
for(int i = 1; i <= musicNum; i++){
cout << i << " ";
}
cout << endl;
// 这里有一点要注意的就是有可能最后的位置超过了musicNum,要取一个模,变到这个范围内
if(curMusicPos >= 0){
cout << (curMusicPos) % musicNum << endl; //
}
else{
cout << (musicNum + curMusicPos + 1) % musicNum << endl;
}
}
else{ //musicNum > 4
int curMusicPos = 1; //当前光标的一个位置
int head = 1, end = 4; //head当前列表的头部是哪一首歌曲, end当前列表尾部是哪一首歌曲
for(char ch : command){
if(ch == 'U') {
curMusicPos--;
//如果光标比第一首歌曲的位置都要小
if(curMusicPos < 1){ //跳到最后一页的位置上面
curMusicPos = musicNum; //更新光标位置
head = musicNum - 4 + 1; //更新列表头部
end = musicNum; //更新列表尾部
}
else{ //如果光标没有小于1
if(curMusicPos < head){ //如果当前位置要比当前的列表头还要小,说明要更新列表了
head = curMusicPos; //更新列表头部
end--; //更新列表尾部
}
}
}
// ch == 'D'
else{
curMusicPos++;
//如果光标比最后一首歌曲的位置都要大
if(curMusicPos > musicNum){ //跳到第一页的位置上面
curMusicPos = 1; //更新光标位置
head = 1; //更新列表头部
end = 4; //更新列表尾部
}
else{ //如果光标没有大于musicNum
if(curMusicPos > end){ //如果当前位置要比当前的列表尾还要大,说明要更新列表了
end = curMusicPos; //更新列表尾部
head++; //更新列表头部
}
}
}
}
//输出
for(int i = head; i <= end; i++){
cout << i << " ";
}
cout << endl;
cout << curMusicPos << endl;
}
return 0;
}
华为题库题解 文章被收录于专栏
牛客华为题库的题解