Need help in a problem of two pointers

Revision ru3, by bovin, 2024-03-28 18:11:56

Problem My code crashes on one of the tests. I assumed it was an overflow problem and tried to fix it, but it didn't work. Now i don't understand what could be the error Code:

#include <iostream>
#include <vector>
 
using namespace std;
 
int f(int n, int m, vector<long long int>& nums1, vector<long long int>&nums2) {
    int i = 0, j = 0;
    long long int count = 0, cnt1, cnt2;
    while(i < n && j < m) {
        if(nums1[i] < nums2[j]) i++;
        else if(nums1[i] > nums2[j]) j++;
        else { // nums1[i] == nums2[j]
            cnt1 = 0, cnt2 = 0;
            int val = nums1[i];
            while(i < n && nums1[i] == val) {
                cnt1++;
                i++;
            }
            while(j < m && nums2[j] == val) {
                cnt2++;
                j++;
            }
            count += cnt1 * cnt2;
        }
    }
    return count;
}
 
int main()
{
    int n, m;
    cin >> n >> m;
    vector<long long int> nums1(n);
    vector<long long int> nums2(m);
    for(int i = 0; i < n; i++) cin >> nums1[i];
    for(int i = 0; i < m; i++) cin >> nums2[i];
    int ans = f(n, m, nums1, nums2);
    cout << ans;
    return 0;
}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English bovin 2024-03-28 21:04:57 1354 Initial revision for English translation
ru5 Russian bovin 2024-03-28 18:12:49 0 (опубликовано)
ru4 Russian bovin 2024-03-28 18:12:25 2 Мелкая правка: ' the error\nCode:\n\n~' -> ' the error.\n#Code:\n\n~'
ru3 Russian bovin 2024-03-28 18:11:56 20
ru2 Russian bovin 2024-03-28 18:10:55 1063
ru1 Russian bovin 2024-03-28 18:09:35 335 Первая редакция (сохранено в черновиках)