dexter04's blog

By dexter04, history, 7 years ago, In English

following code does not work for input 1 10000. but it works when I use p as loop breaker why is that...

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define pll pair<long long,long long>

vector<pll>v;
int main()
{
    int n;
    cin>>n;
    ll a[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n,greater<ll>());
    ll ans=0;

    for(int i=0;i<n-1;i++)
    {
        if(a[i]-a[i+1]<2)
        {
            v.push_back(pll(a[i],a[i+1]));
            i++;
        }
    }
    int p=v.size()-1;
    for(int i=0;i<v.size()-1;i+=2)
    {
        pll x=v[i],y=v[i+1];
        ans+=x.second*y.second;
    }
    cout<<ans;
}
  • Vote: I like it
  • -7
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it +12 Vote: I do not like it

That's because vector::size function returns an unsigned integer value and you're subtracting a signed integer from that. When an expression contains both signed and unsigned int values, the signed int will be automatically converted to unsigned int and so the result will not be less than 0.

So what you can do is explicitly type cast the value returned by vector::size function maybe like this - (int)v.size() - 1 and hopefully it'll work fine.

  • »
    »
    7 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    but when I assigned the value v.size()-1 to p it worked why is that if I am using the same expression

    • »
      »
      »
      7 years ago, # ^ |
        Vote: I like it -8 Vote: I do not like it

      Because int p = something has the same behavior as p = (int) something