fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <functional> // std::hash
  5.  
  6. using namespace std;
  7.  
  8. // Hàm băm đơn giản cho số nguyên
  9. size_t hash_int(int val) {
  10. hash<int> hasher;
  11. return hasher(val);
  12. }
  13.  
  14. int main() {
  15. int n, q;
  16. cin >> n >> q;
  17.  
  18. vector<int> a(n);
  19. for (int i = 0; i < n; ++i) {
  20. cin >> a[i];
  21. }
  22.  
  23. // Kích thước bảng băm (nên chọn số nguyên tố lớn hơn n để giảm va chạm)
  24. int hash_table_size = 2 * n + 1;
  25. vector<vector<int>> hash_table(hash_table_size);
  26.  
  27. // Xây dựng bảng băm
  28. for (int i = 0; i < n; ++i) {
  29. size_t hash_value = hash_int(a[i]) % hash_table_size;
  30. hash_table[hash_value].push_back(i + 1); // Lưu trữ chỉ số 1-based
  31. }
  32.  
  33. for (int i = 0; i < q; ++i) {
  34. string type_str;
  35. int type_val, y_val;
  36. cin >> type_str >> type_val >> y_val;
  37.  
  38. size_t hash_value = hash_int(y_val) % hash_table_size;
  39. vector<int>& indices = hash_table[hash_value];
  40.  
  41. int first = -1;
  42. int last = -1;
  43.  
  44. for (int index : indices) {
  45. if (a[index - 1] == y_val) {
  46. if (first == -1) {
  47. first = index;
  48. }
  49. last = index;
  50. }
  51. }
  52.  
  53. if (type_val == 1) {
  54. cout << first << endl;
  55. } else if (type_val == 2) {
  56. cout << last << endl;
  57. }
  58. }
  59.  
  60. return 0;
  61. }
Success #stdin #stdout 0.01s 5288KB
stdin
13 6

9 10 12 7 -1 1 1 0 1 7 9 9 1

type 1 3

type 2 2

type 1 1

type 2 1

type 1 9

type 2 7
stdout
-1
-1
6
13
1
10