bovin's blog

By bovin, history, 4 weeks ago, translation, In English

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;
}
  • Vote: I like it
  • +1
  • Vote: I do not like it

»
4 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Your code is still having an overflow problem. Since ans can be very large, even greater than int range, you must take it as long long. Also, don't forget to change function f return type int to long long.

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thank you so much, I was so inattentive