Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- typedef long long int ll;
- ll long_ceil(ll x, ll y)
- {
- ll ans=x/y;
- if(x%y!=0)
- ans++;
- return ans;
- }
- int main()
- {
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- #endif
- ios_base::sync_with_stdio(false);
- ll i,j,fac[21];
- fac[0]=1;
- for(i=1;i<21;i++)
- fac[i]=fac[i-1]*i;
- ll k,q;
- string str;
- cin>>str>>q;
- k=str.size();
- //only for testing purpose - not part of soln
- set <char> s;
- set <char>::iterator it;
- for(i=0;i<k;i++) {
- j=(ll)str[i];
- assert(j>=97 && j<=122);
- s.insert(str[i]);
- }
- ll k1=s.size(),f=0; //f- flag to check whether all characters are distinct
- if(k==k1)
- f=1;
- assert(f==1);
- assert(k>=1 && k<=20);
- assert(q>=1 && q<=1000);
- //testing part ends. solution continues.
- ll p[k+1],pc[k+1][k+1]; //p-permutation array; pc-precomp array
- for(i=0;i<=k;i++) {
- p[i]=fac[k]/fac[k-i];
- for(j=0;j<=k;j++)
- pc[i][j]=0;
- }
- for(i=1;i<=k;i++) {
- for(j=i;j<=k;j++) {
- if(i==1)
- pc[i][j]=p[j]/k;
- else
- pc[i][j]=pc[i-1][j]/(k+1-i);
- }
- }
- ll l[k+1]; //l-reqd. strings' Length determining array
- l[0]=0; l[1]=pc[1][1];
- for(i=2;i<=k;i++)
- l[i]=l[i-1]+pc[1][i];
- ll ts=l[k]*k; //ts-total no of all possible permutation of strings
- while(q--) {
- ll x,ct,t,t2,t3; //ct - length of expected string; t,...,t3 - tem variables
- cin>>x;
- assert(x>0); //queries tested.
- if(x>ts) {
- cout<<ts<<"\n";
- continue;
- }
- set <char> s;
- set <char>::iterator it;
- for(i=0;i<k;i++)
- s.insert(str[i]);
- string ans="";
- char c;
- t=long_ceil(x,l[k]);
- x-=((t-1)*l[k]);
- for(i=0;i<k;i++) {
- if(x>l[i] && x<=l[i+1]) {
- break;
- }
- }
- ct=t2=i+1;
- it=s.begin();
- for(i=1;i<t;i++)
- it++;
- c=(*it); ans+=c; ct--;
- s.erase(it); x-=l[ct];
- while(ct>0) {
- t3=pc[t2+1-ct][t2];
- t=long_ceil(x,t3);
- it=s.begin();
- for(i=1;i<t;i++)
- it++;
- c=(*it); ans+=c; ct--;
- s.erase(it); x-=((t-1)*t3);
- }
- cout<<ans<<"\n";
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment