Problem Link (Problem - 1311C - Codeforces)
My Solution is given tle. Please Help.
#include<bits/stdc++.h>
#define fast ios_base::sync_with_stdio(false);cin.tie(0);
#define lli long long int
#define vi vector<lli>
#define Q queue<lli>
#define vii vector<pair<lli,lli> >
#define pb push_back
#include<string>
#define mp map<string,lli>
#define mpp map<char,lli>
#define MPP map<lli,lli>
#define P pair<lli,lli>
#define ss set<lli>
#define MOD 1000000007
#define test lli t;cin>>t;while(t--)
using namespace std;
const int MAX=1e7+10;
int main()
{
test
{
lli n,m;
cin>>n>>m;
string s,s1;
vector<string>a;
mpp ar;
for(char x='a';x<='z';x++)
ar[x]=0;
cin>>s;
vi arr(m);
for(auto &it:arr)
cin>>it;
for(lli i=0;i<m;i++)
{
for(lli j=0;j<arr[i];j++)
ar[s[j]]+=1;
}
for(lli i=0;i<s.size();i++)
ar[s[i]]+=1;
for(char a='a';a<='z';a++)
cout<<ar[a]<<" ";
cout<<endl;
}
}
better to first sort the p array and then work with this like:
assume p array is 3 4 2 1 6 7
sorted p : 1 2 3 4 6 7
so what it means first latter will come n th time 2 nd come n-1 third n-2 fourth n-4 5 th n-5 6th n-5 7th n-6 like that where n is size of p th array
increase like this inplace of running 1 by 1
Try considering the total times we are moving and adding the same except adding one each time.
Solution
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
void solve()
{
ll n,m,x,y,i,j,k;
cin>>n>>m;
string s;
unordered_map<char,int> mp;
cin>>s;
for(j=0;j<n;j++)
mp[s[j]]++;
std::vector<int> a(m);
for(auto &t:a)
{
cin>>t;
}
sort(a.begin(), a.end());
k=0;
for(i=0;i<m;i++)
{
while(k<a[i])
{
mp[s[k]]+=m-i;
k++;
}
}
for(char c='a';c<='z';c++)
{
cout<<mp[c]<<" ";
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("error.txt", "w", stderr);
freopen("output.txt", "w", stdout);
#endif
int t=1;
// cout<<t<<endl;
// ${2:is Single Test case?}cin>>t;
cin>>t;
while(t--)
{
solve();
cout<<"\n";
}
cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
return 0;
}
Check the following simple array-based solution with sorting or using map.
Accepted