Code for WRDVLS problem from startes 20 giving wrong answer

I was watching the editorial of weird values problem and copied the code from there with one modificaiton.
I replaced for(int i=1;i<(int)(size(indsx))-x;i++) with for(ll i=1;i<indsx.size()-x;i++) and it is giving segmentation fault on submitting. Although, it is passing the sample test cases.
Can someone guide me why?

#include"bits/stdc++.h"
#define ll long long int
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll t;
    cin>>t;
    while(t--)
    {
        ll n;
        cin>>n;
        
        vector<vector<ll>> inds(n+1);
        for(ll i=1;i<=n;i++)
        {
            ll x;
            cin>>x;
            if(x<=n)
              inds[x].push_back(i);
        }

        ll ans=0;
        for(ll x=1;x<=n;x++)
        {
            vector<ll> indsx=inds[x];
            indsx.insert(begin(indsx),0);
            indsx.push_back(n+1);
            for(ll i=1;i<indsx.size()-x;i++)
            {
                ans+=x*(indsx[i]-indsx[i-1])*(indsx[i+x]-indsx[i+x-1]);

            }

        }
cout<<ans<<"\n";
        


    }

    return 0;
}```

damn, that was a nice blog.
It cleared most of my doubts that why my this code is incorrect.
But, I have been using the same syntax that is i<vector.size() from a long time. did I not face this kind of problem before?
is it because condition if(x<=n) may cause the indsx array to be empty for that value of x and we may encounter the condition of i<indsx.size() compute to i<-1 in that case?

Actually, there’s nothing wrong with the following code.

for(int i=0;i<a.size();i++){
   
}

But here you’re actually doing some arithmetic like,

for(int i=0;i<a.size()-x;i++){
   
}

this leads to implicit conversions like typecasting i from int to size_t which causes issues. Hence it’s best to typecast a.size() to int whenever you’re using it.

Thanks for clarificaiton.
I really appreciate the patience you had while answering my queries.

1 Like