2022.01.29刷題
阿新 • • 發佈:2022-01-29
acwing 資料結構
陣列模擬單鏈表
int idx, head, ne[N5], e[N5]; int main() { int n = read(), k, x; head = -1; //初始化頭結點 char op; while (n--) { scanf("%c", &op); k = read(); if (op == 'H') { e[idx] = k; ne[idx] = head; head = idx++; } else if (op == 'D') { if (k == 0) { head = ne[head]; } else ne[k - 1] = ne[ne[k - 1]]; } else { x = read(); ne[idx] = ne[k - 1]; ne[k - 1] = idx; e[idx++] = x; } } while (head != -1) { O(e[head]); head = ne[head]; } return 0; }
陣列模擬雙鏈表
int idx, head, l[N5], e[N5], r[N5]; void init() { r[0] = 1, l[1] = 0, idx = 2; } void insert(int k, int x) { l[idx] = k, r[idx] = r[k], e[idx] = x; l[r[k]] = idx, r[k] = idx++; } void remove(int k) { r[l[k]] = r[k], l[r[k]] = l[k]; } int main() { init(); int k, x, m = read(); string op; while (m--) { cin >> op;k = read(); if (op[0] == 'R') insert(l[1], k); else if (op[0] == 'L') insert(0, k); else if (op[0] == 'I') { x = read(); if (op[1] == 'R') insert(k + 1, x); else insert(l[k + 1], x); } else remove(k + 1); } head = r[head]; while (head != 1) O(e[head]), head = r[head]; return 0; }
模擬棧
雪菜有的是 從 tt=0
不知道有沒有影響.
然後empty() 是 tt>0
int stk[N5], tt = -1; //記住下標是從 -1 開始的
void push(int x) {
stk[++tt] = x;
}
void pop() {
--tt;
}
int query() {
return stk[tt];
}
bool empty() {
return tt == -1;
}
模擬佇列
int q[N5], tt = -1, hh; void push(int x) { q[++tt] = x; } void pop() { ++hh; } int query() { return q[hh]; } bool empty() { return hh > tt; }
單調棧
int a[N6], tt;
int main() {
int n = read(), x;
rep(i, 0, n) {
x = read();
while (tt && a[tt] >= x) tt--;
if (tt) O(a[tt]);
else O(-1);
a[++tt] = x;
}
return 0;
}
滑動視窗最大值和最小值.
int a[N6], q[N6], tt = -1, hh;
int main() {
int n = read(), k = read();
rep(i, 0, n) a[i] = read();
rep(i, 0, n) {
if (hh <= tt && i - k + 1 > q[hh]) hh++;
while (hh <= tt && a[q[tt]] >= a[i]) tt--; //最小值, 單增區間
q[++tt] = i;
if (i - k + 1 >= 0) O(a[q[hh]]);
}
puts("");
tt = -1, hh = 0;
rep(i, 0, n) {
if (hh <= tt && i - k + 1 > q[hh]) hh++;
while (hh <= tt && a[q[tt]] <= a[i]) tt--; //最大值, 單減區間
q[++tt] = i;
if (i - k + 1 >= 0) O(a[q[hh]]);
}
return 0;
}
表示式求值
不會做... 不過這個順序..
stack<int> op;
stack<int> num;
void eval() {
auto b = num.top(); num.pop();
auto a = num.top(); num.pop();
auto c = op.top();op.pop();
int x;
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main() {
unordered_map<char, int> pri = { {'+',1},{'-',1},
{'*',2},{'/',2} };
string equ;
cin >> equ;
for (int i = 0;i < equ.size();i++) {
auto c = equ[i];
if (isdigit(c)) {
int x = 0, j = i;
while (j < equ.size() && isdigit(equ[j]))
x = x * 10 + equ[j++] - '0';
i = j - 1; num.push(x);
}
else if (c == '(') op.push(c);
else if (c == ')') {
while (op.top() != '(') eval();
op.pop();
}
else {
while (op.size() && op.top() != '(' &&
pri[op.top()] >= pri[c]) eval();
op.push(c);
}
}
while (op.size()) eval();
cout << num.top() << endl;
return 0;
}