Sicily 1443. Printer Queue

来源:互联网 发布:国内可备案的域名 编辑:程序博客网 时间:2024/05/16 09:15

· 个人认为这题比较有意义,考察了如何用数组模拟一个队列,并执行相应操作。虽然想起来比较简单,但真正实现时有许多细节比较容易忽略,应多熟悉练习。

· 此代码写得有点冗长,while(true) 后面的两大块其实是可以合并的。。。当时没考虑太多就写了。改天来简化一下。

代码如下:



#include <iostream>using namespace std;int main(){int cases;cin >> cases;while(cases --){int n,pos,head,end,target,cur,cnt = 0; // head: 头指针,end: 为指针,target: 目标数 cin >> n >> pos;   // cur: 当前位置 cnt: 时间 pos: target下标int *que = new int[n];for(int i = 0;i < n;i ++)cin >> que[i];head = 0,end = n - 1;target = que[pos];cur = head;bool mark = false;while(true){if (cur == pos){for (int i = (cur + 1) % n;i != (end + 1) % n;i = (i + 1) % n){if (que[i] > que[pos]) // target放在队列尾{head = (head + 1) % n;end = (end + 1) % n;que[end] = que[pos];pos = end; // 别忘了更pos的值mark = true;break;}}cur = (cur + 1) % n;if (mark){mark = false;continue;}cnt ++;cout << cnt << endl;  // 否则输出时间,结束此轮循环break;}else{int tem = que[cur];for (int i = (cur + 1) % n;i != (end + 1) % n;i = (i + 1) % n){if (que[i] > tem) // target放在队列尾{head = (head + 1) % n;end = (end + 1) % n;que[end] = tem;mark = true;break;}}cur = (cur + 1) % n;if (mark){mark = false;continue;}head = (head + 1) % n; //否则,队列首元素出队,头指针后移一位cnt ++;}}delete [] que;}}                                 


原创粉丝点击