Untitled
unknown
plain_text
a year ago
1.5 kB
10
Indexable
#include <iostream>
#include <unordered_map>
#include <vector>
#include <utility>
using namespace std;
int main() {
// Khai báo unordered_map
unordered_map<int, vector<pair<int, int>>> mp;
// Giả sử ma trận có kích thước 3x3
int n = 3;
int matrix[3][3] = {
{1, 2, 1},
{3, 1, 2},
{2, 3, 3}
};
// Duyệt qua ma trận và cập nhật unordered_map
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int key = matrix[i][j];
int coordinate = i * n + j;
// Nếu key chưa tồn tại trong map, thêm nó vào
if (mp.find(key) == mp.end()) {
mp[key] = vector<pair<int, int>>();
}
// Nếu vector rỗng hoặc key xuất hiện lần đầu ở vị trí mới
if (mp[key].empty() || mp[key].back().second != coordinate) {
mp[key].push_back({1, coordinate});
} else {
// Tăng số lần xuất hiện
mp[key].back().first++;
}
}
}
// In kết quả
for (const auto& entry : mp) {
cout << "Key " << entry.first << ":" << endl;
for (const auto& p : entry.second) {
int row = p.second / n;
int col = p.second % n;
cout << " Xuất hiện " << p.first << " lần tại vị trí ("
<< row << ", " << col << ")" << endl;
}
cout << endl;
}
return 0;
}Editor is loading...
Leave a Comment