/* * ******************************************************************************************** * AUTHOR : Vijju123 * * Language: C++14 * * Purpose: - * * IDE used: Codechef IDE. * ******************************************************************************************** * Comments will be included in practice problems if it helps ^^ */ #include #include using namespace std; int main() { // your code goes here #ifdef JUDGE freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--) { int n; string s; cin>>s>>n; int a=0,b=0,goodPrefix=0; for(auto i:s) { if(i=='a')a++; else b++; if(a>b)goodPrefix++; } if(n==1)cout<b or a Atmost 1000 iterations worth simulation needed. If new prefixes decrement, then after //at most 1000 iterations new appendations will have 0 contribution to answer- and if //new prefixes increment, after 1000 iterations their value will be 1000 (=length of string) //We can calculate both these cases by formula string t=""; int incr=-1,i=0; long long ans=0,prevAns=0; int k=s.length(),tempN=n; a=0; b=0; while(tempN-- and incr!=k and incr!=0)//If change !=length of string and !=0 { t+=s; for(;ib) { ++ans; } } incr=ans-prevAns;//change in final answer. prevAns=ans; } incr=max(incr,0);//In case incr goes negative ans+=1LL*(tempN+1)*incr;//Why tempN+1? Focus on "tempN--". when tempN becomes 0, it goes to "0--= -1" cout<