2 条题解
-
0
B3616 【模板】队列——题解
思路
用数组模拟队列,设置两个下标:
head指向当前队首;tail指向下一个可写入位置。
于是:
- 入队:
q[tail++] = x; - 队列为空:
head == tail; - 出队:若非空则
head++; - 查询队首:
q[head]; - 队列大小:
tail - head。
复杂度
每条操作时间复杂度 ,空间复杂度 。
参考代码
#include <bits/stdc++.h> using namespace std; int q[10005]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; int head = 0, tail = 0; while (n--) { int op; cin >> op; if (op == 1) { int x; cin >> x; q[tail++] = x; } else if (op == 2) { if (head == tail) cout << "ERR_CANNOT_POP\n"; else head++; } else if (op == 3) { if (head == tail) cout << "ERR_CANNOT_QUERY\n"; else cout << q[head] << '\n'; } else { cout << tail - head << '\n'; } } return 0; } -
0
#include <bits/stdc++.h> using namespace std; int q[10005]; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin>>n; int head=0,tail=0; while(n--){ int op; cin>>op; if(op1){ int x; cin>>x; q[tail++]=x; } else if(op2){ if(headtail) cout<<"ERR_CANNOT_POP\n"; else head++; } else if(op3){ if(head==tail) cout<<"ERR_CANNOT_QUERY\n"; else cout<<q[head]<<'\n'; } else cout<<tail-head<<'\n'; } return 0; }
- 1
信息
- ID
- 4943
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 10
- 标签
- 递交数
- 3
- 已通过
- 2
- 上传者
粤公网安备44195502000195号