E - 內存管理
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
2
Create 1 30
Create 2 20
Create 3 30
Create 4 100
Delete 4
Delete 2
Delete 3
End
Create 1 100
End
Sample Output
Create process 1 of size 30 successfully!
Create process 2 of size 20 successfully!
Create process 3 of size 30 successfully!
P 1 30
P 2 20
P 3 30
H 20
No enough memory!
No such process!
Delete process 2 of size 20 successfully!
P 1 30
H 20
P 3 30
H 20
Delete process 3 of size 30 successfully!
P 1 30
H 70
Create process 1 of size 100 successfully!
P 1 100
其實這道題就根據題目意思一步一步來寫就可以了,簡單是簡單,但是很煩,細節要注意,尤其是關於頭和尾的操作要單獨算,也不要忘記把相鄰的空內存合並,發現很多人都用鏈表寫的,表示還沒學哇,就用vector寫了一個,應該還是很好理解的。
代碼如下:
#include#include #include #include #include using namespace std; char str[100]; int arr[105]; struct node { int id; char state; int size; }; vector G; int main() { int t, tmp, msize, flag, a, j; scanf("%d", &t); while(t--) { node in; in.id = 0; in.state = 'H'; in.size = 100; G.push_back(in); while(~scanf("%s", str)) { if(strcmp(str, "End") == 0) break; if(strcmp(str, "Create") == 0) { scanf("%d%d", &in.id, &in.size); tmp = 0, msize = 200; for(int i = 0; i < G.size(); i++) { if(G[i].state == 'H') { if(G[i].size >= in.size && G[i].size < msize) { msize = G[i].size; tmp = i; } } } if(msize == 200) printf("No enough memory!\n"); else { in.state = 'P'; G[tmp].size -= in.size; G.insert(G.begin()+tmp, in); if(G[tmp].size == 0) { G.erase(G.begin() + tmp); } printf("Create process %d of size %d successfully!\n", in.id, in.size); } } if(strcmp(str, "Print") == 0) { for(int i = 0; i < G.size(); i++) { if(G[i].state == 'P') printf("%c %d %d\n", G[i].state, G[i].id, G[i].size); else if(G[i].size != 0) printf("H %d\n", G[i].size); } } if(str[0] == 'D') { flag = 1; scanf("%d", &a); for(j = 0; j < G.size(); j++) { if(G[j].id == a && G[j].state == 'P') { printf("Delete process %d of size %d successfully!\n", a, G[j].size); a = 0; G[j].state = 'H'; if(j == 0) { if(G[1].state == 'H') { G[0].size += G[1].size; G.erase(G.begin() + 1); } } else { if(j == G.size()) { if(G[j-1].state == 'H') { G[j-1].size += G[j].size; G.erase(G.begin() + j); } } else { if(G.size() > 1) { if(G[j-1].state == 'H') { G[j].size += G[j-1].size; G.erase(G.begin()+j-1); flag = 0; } if(G[j+flag].state == 'H') { G[j+flag-1].size += G[j+flag].size; G.erase(G.begin()+j+flag); } } break; } } } } if(a != 0) printf("No such process!\n"); } } G.clear(); } return 0; }