vendredi 23 juillet 2021

C++ custom sort a 2d vector throwing runtime error. How do I fix this?

I am trying to sort the 2D vector on basis of the difference between the character count of a particular character and the rest of the characters. It works fine for most of the test cases, but it seems to fail for this particular testcase. After some debugging, I found out that it is getting a runtime error when ch='d' and ch='e' for the following testcase. I am not able to figure out what exactly is happening here.

void solve()
{
    ll n;
    string s;
    cin>>n;
    vector<vector<ll>>v(n,vector<ll>(5,0));
    unordered_map<char, ll>m;
    vector<string>str;
    unordered_map<char, ll>old;
    for(ll i=0;i<n;i++)
    {   
        cin>>s;
        str.push_back(s);
    }
    for(ll i=0;i<n;i++)
    {   
        for(ll j=0;j<str[i].length();j++)
        {
            v[i][str[i][j]-97]++;
            m[str[i][j]]++;
        }
    }
    old=m;
    ll ans=0;
    for(char ch='a';ch<='e';ch++)
    {  
        m=old;
        ll sum=m['a']+m['b']+m['c']+m['d']+m['e'];
        if(sum-m[ch]<m[ch])
        {
            ans=max(ans,n);
        }
        sort(v.begin(),v.end(),[ch](const vector<ll>&a,const vector<ll>&b)
        {   
            return (a[ch-97]-(a[0]+a[1]+a[2]+a[3]+a[4]))<=(b[ch-97]-(b[0]+b[1]+b[2]+b[3]+b[4]));
        });
     
        for(ll i=0;i<n;i++)
        {   
            for(ll j=0;j<5;j++)
            {   
                m[j+97]=m[j+97]-v[i][j];
            }
            ll sumrest=m['a']+m['b']+m['c']+m['d']+m['e'];
            if(m[ch]>sumrest-m[ch])
            {
                ans=max(ans,n-i-1);
            }  
        }
    }
    cout<<ans<<"\n";
}

Testcase:-

1
43
a
d
bbc
a
dda
c
e
bb
cbd
c
dc
e
caab
d
c
e
e
bd
d
a
a
b
a
c
d
c
d
ba
e
c
ecdb
bdbd
d
e
cb
ac
ccd
cb
cda
da
bb
d
c

Aucun commentaire:

Enregistrer un commentaire