Untitled
unknown
plain_text
a year ago
1.8 kB
9
Indexable
#include <iostream>
#include <map>
#include <unordered_map>
using namespace std;
const int MAX_ID = 50001;
int n, m;
unordered_map<int, pair<int, int>> wordInfo; // {mId -> {row, startCol}}
map<int, int> rowSpaces; // {row -> remaining slots}
void init(int N, int M) {
n = N;
m = M;
wordInfo.clear();
rowSpaces.clear();
for (int i = 0; i < n; ++i) {
rowSpaces[i] = m; // Mỗi hàng đều bắt đầu với M chỗ trống
}
}
int writeWord(int mId, int mLen) {
// Tìm hàng có đủ chỗ trống để chứa từ
for (auto it = rowSpaces.begin(); it != rowSpaces.end(); ++it) {
int row = it->first;
int availableSpace = it->second;
if (availableSpace >= mLen) {
int startCol = m - availableSpace; // Vị trí bắt đầu của từ
// Ghi lại thông tin từ
wordInfo[mId] = {row, startCol};
// Cập nhật lại số chỗ trống
rowSpaces[row] -= mLen;
if (rowSpaces[row] == 0) {
rowSpaces.erase(row); // Nếu không còn chỗ trống, xóa hàng khỏi map
}
return row;
}
}
return -1; // Không có hàng nào đủ chỗ trống
}
int eraseWord(int mId) {
if (wordInfo.find(mId) == wordInfo.end()) {
return -1; // Từ không tồn tại
}
int row = wordInfo[mId].first;
int startCol = wordInfo[mId].second;
int mLen = m - startCol; // Chiều dài của từ
// Cập nhật lại số chỗ trống cho hàng này
rowSpaces[row] += mLen;
// Xóa thông tin từ khỏi map
wordInfo.erase(mId);
return row;
}
Editor is loading...
Leave a Comment