สมมติว่าเรารับผิดชอบในการสร้างระบบห้องสมุดที่คอยตรวจสอบและสอบถามการดำเนินการต่างๆ ที่ห้องสมุด เราถูกขอให้ใช้คำสั่งที่แตกต่างกันสามคำสั่งซึ่งดำเนินการดังต่อไปนี้ -
-
โดยใช้คำสั่ง 1 เราสามารถบันทึกการแทรกหนังสือที่มีหน้า y ที่ชั้น x
-
โดยใช้คำสั่ง 2 เราสามารถพิมพ์เลขหน้าของหนังสือเล่มที่ y ที่ชั้น x ได้
-
โดยใช้คำสั่ง 3 เราสามารถพิมพ์จำนวนหนังสือบนชั้น x ได้
คำสั่งต่างๆ มอบให้เราในรูปแบบอาร์เรย์ 2 มิติในรูปแบบนี้ {command type, x, y} หากไม่มีค่า y ค่านั้นจะเริ่มต้นที่ 0 เราพิมพ์ผลลัพธ์ของคำสั่งที่กำหนด
ดังนั้น หากอินพุตเหมือนกับจำนวนชั้นวาง =4 ข้อความค้นหา =4, input_arr ={{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0 }}; แล้วผลลัพธ์ที่ได้จะเป็น
23 1
Command 1 inserts a book with 23 pages on shelf 3. Command 2 inserts a book with 128 pages on shelf 4. Command 3 prints the page number of book 0 on shelf 3. Command 4 prints the number of books on shelf 3.
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
- b :=อาร์เรย์ใหม่ขนาด s
- p :=อาร์เรย์ใหม่ขนาด s
- สำหรับการเริ่มต้น i :=0, เมื่อ i
- b[i] :=0
- p[i] :=อาร์เรย์ใหม่
qtype :=q_array[loopCount, 0] ถ้า qtype เหมือนกับ 1 แล้ว −
- x :=q_array[loopCount, 1]
- y :=q_array[loopCount, 2]
- b[x] :=b[x] + 1
- p[x] :=จัดสรรคืนวัตถุที่ชี้โดย p[x] และคืนค่าตัวชี้ของขนาด
- b[x]
- p[x, b[x] - 1] =y
มิฉะนั้นเมื่อ qtype เหมือนกับ 2 แล้ว −
- x :=q_array[loopCount, 1]
- y :=q_array[loopCount, 2]
- พิมพ์(p[x, y])
มิฉะนั้น
- x :=q_array[loopCount, 1]
- พิมพ์(b[x])
- จัดสรรหน่วยความจำที่ได้รับจาก b
- จัดสรรหน่วยความจำที่ได้รับโดย p[i]
- จัดสรรหน่วยความจำที่ได้รับโดย p
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <stdio.h>
#include <stdlib.h>
void solve(int s, int q, int q_array[][3])
{
int* b;
int** p;
b = (int*)malloc(sizeof(int)*s);
p = (int**)malloc(sizeof(int*)*s);
for(int i = 0; i < s; i++)
{
b[i] = 0;
p[i] = (int*)malloc(sizeof(int));
}
int loopCount;
for(loopCount = 0; loopCount < q; loopCount++)
{
int qtype;
qtype = q_array[loopCount][0];
if (qtype == 1)
{
int x, y;
x = q_array[loopCount][1];
y = q_array[loopCount][2];
b[x] += 1;
p[x] = realloc(p[x], b[x]*sizeof(int));
p[x][b[x] - 1] = y;
}
else if (qtype == 2)
{
int x, y;
x = q_array[loopCount][1];
y = q_array[loopCount][2];
printf("%d\n", p[x][y]);
}
else
{
int x;
x = q_array[loopCount][1];
printf("%d\n", b[x]);
}
}
if (b)
free(b);
for (int i = 0; i < s; i++)
if (p[i])
free(p[i]);
if (p)
free(p);
}
int main() {
int input_arr[][3] = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}};
solve(4, 4, input_arr);
} อินพุต
int input_arr[][3] = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}};
solve(4, 4, input_arr); ผลลัพธ์
23 1