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

#define ll long long
const int INF = 1e9;

ll gcd(ll a,ll b){
	return b==0?gcd(b,a%b):a;
}

int main(){

	ll m,h1,a1,x1,y1;
	ll   h2,a2,x2,y2;
	cin>>m;
	cin>>h1>>a1;
	cin>>x1>>y1;
	cin>>h2>>a2;
	cin>>x2>>y2;

	//
	ll ans1=1;
	for(;ans1<=m;ans1++){
		h1=x1*h1+y1;
		h1%=m;
		if(h1==a1)break;
	}

	ll ans2=1;
	for(;ans2<=m;ans2++){
		h2=x2*h2+y2;
		h2%=m;
		if(h2==a2)break;
	}

	bool ok=1;
	if(ans1>m||ans2>m)ok=0;

	if(ok){
		ll ans=ans1*ans2/gcd(ans1,ans2);
		cout<<ans;
	}else{
		cout<<"-1";
	}

	return 0;
}

/*
#define ll long long
const int INF=1e9;

int mp[110][110];
int lv[110];
bool dp[110][110];
int n;
vector<int> s0[110];
vector<int> s1[110];
int groupcnt;
int pre[110][110];

int re;
int tmp;
void dfs(int u){
//	cout<<"dfsing "<<u<<endl;
	if(lv[u]){
		s0[groupcnt].push_back(u);
		tmp--;
	}else{
		s1[groupcnt].push_back(u);
		tmp++;
	}
	for(int v=1;v<=n;v++){
		if(v==u)continue;
		if(!(mp[u][v]&&mp[v][u])){
			if(lv[v]!=-1){
				if((lv[v]&1)==(lv[u]&1)){
					return;
				}else{
					continue;
				}
			}
			lv[v]=!lv[u];
			dfs(v);
		}
	}
}

void init(){
	memset(mp,0,sizeof(mp));
	memset(lv,-1,sizeof(lv));
	memset(dp,0,sizeof(dp));
	memset(s0,0,sizeof(s0));
	memset(s1,0,sizeof(s1));
}

int main(){
	//int t;
	//cin>>t;
	while(cin>>n){

		init();

		//cin>>n;
		for(int i=1;i<=n;i++){
			int num;
			while(scanf("%d",&num)){
				if(!num)break;
				mp[i][num]=1;
			}
		}

		dp[0][0]=1;
		groupcnt=0;
		for(int i=1;i<=n;i++){
			if(lv[i]==-1){
				lv[i]=0;
				groupcnt++;
				tmp=0;
				dfs(i);
				//cout<<i<<" "<<tmp<<endl;

				for(int j=0;j<=n/2;j++){
					if(dp[groupcnt-1][j]){
						if(j+tmp>=0){
							dp[groupcnt][j+tmp]=1;
							pre[groupcnt][j+tmp]=j;
						}
						if(j-tmp>=0){
							dp[groupcnt][j-tmp]=1;
							pre[groupcnt][j-tmp]=j;
						}
					}
				}
			}
		}

		int ans=0;
		for(int i=0;i<=n;i++){
			if(dp[groupcnt][i]){
				ans=i;break;
			}
		}

		bool ok=1;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(i==j)continue;
				if( !(mp[i][j]&&mp[j][i]) ){
					if(lv[i]==lv[j]){
						ok=0;
					}
				}
			}
		}

		if(ok){
			//cout<<ans<<endl;
			int cur=ans;
			vector<int> ans0;
			vector<int> ans1;
			for(int i=groupcnt;i>=1;i--){
				int p=pre[i][cur];

				vector<int> &big=s0[i];
				vector<int> &small=s1[i];
				if(big.size()<small.size()){
					swap(big,small);
				}

				//cout<<"�󼯺�size"<<big.size()<<" С����size"<<small.size()<<endl;

				if(p<cur)swap(big,small);

				for(int j=0;j<big.size();j++){
					ans0.push_back(big[j]);
				}
				for(int j=0;j<small.size();j++){
					ans1.push_back(small[j]);
				}

				cur=p;
			}
			cout<<ans0.size()<<" ";
			for(int i=0;i<ans0.size();i++){
				cout<<ans0[i]<<" ";
			}cout<<endl;
			cout<<ans1.size()<<" ";
			for(int i=0;i<ans1.size();i++){
				cout<<ans1[i]<<" ";
			}cout<<endl;
		}else{
			cout<<"No solution"<<endl;
		}
		//if(t)cout<<endl;
	}
	return 0;
}*/


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

#define ll long long
const int INF = 1e9;

ll gcd(ll a,ll b){
	if(b==0)return a;
	return gcd(b,a%b);
}

ll MIN(ll a,ll b){
	if(a>b)return b;
	return a;
}

set<ll> s1;
set<ll> s2;

int main(){

	ll m,h1,a1,x1,y1;
	ll   h2,a2,x2,y2;
	cin>>m;
	cin>>h1>>a1;
	cin>>x1>>y1;
	cin>>h2>>a2;
	cin>>x2>>y2;

	//
	ll ans1=1;
	for(;ans1<=m+1;ans1++){
		h1=x1*h1+y1;
		h1%=m;
		if(h1==a1){
			break;
		}
	}

	ll ans2=1;
	for(;ans2<=m+1;ans2++){
		h2=x2*h2+y2;
		h2%=m;
		if(h2==a2){
			break;
		}
	}

	ll cyc1=1;
	for(;cyc1<=m+1;cyc1++){
		h1=x1*h1+y1;
		h1%=m;
		if(h1==a1){
			break;
		}
	}

	ll cyc2=1;
	for(;cyc2<=m+1;cyc2++){
		h2=x2*h2+y2;
		h2%=m;
		if(h2==a2){
			break;
		}
	}

	bool ok=1;
	if(ans1>m+1||ans2>m+1)ok=0;

	if(ok){
		ll ans=10000000000000LL;
		for(int i=0;i<=100;i++){
			for(int j=0;j<=100;j++){
				ll tmp1=ans1+i*cyc1;
				ll tmp2=ans2+j*cyc2;
				ans=MIN(ans, tmp1*tmp2/gcd(tmp1,tmp2) );
			}
		}
		cout<<ans;
	}else{
		cout<<"-1";
	}

	return 0;
}

/*
#define ll long long
const int INF=1e9;

int mp[110][110];
int lv[110];
bool dp[110][110];
int n;
vector<int> s0[110];
vector<int> s1[110];
int groupcnt;
int pre[110][110];

int re;
int tmp;
void dfs(int u){
//	cout<<"dfsing "<<u<<endl;
	if(lv[u]){
		s0[groupcnt].push_back(u);
		tmp--;
	}else{
		s1[groupcnt].push_back(u);
		tmp++;
	}
	for(int v=1;v<=n;v++){
		if(v==u)continue;
		if(!(mp[u][v]&&mp[v][u])){
			if(lv[v]!=-1){
				if((lv[v]&1)==(lv[u]&1)){
					return;
				}else{
					continue;
				}
			}
			lv[v]=!lv[u];
			dfs(v);
		}
	}
}

void init(){
	memset(mp,0,sizeof(mp));
	memset(lv,-1,sizeof(lv));
	memset(dp,0,sizeof(dp));
	memset(s0,0,sizeof(s0));
	memset(s1,0,sizeof(s1));
}

int main(){
	//int t;
	//cin>>t;
	while(cin>>n){

		init();

		//cin>>n;
		for(int i=1;i<=n;i++){
			int num;
			while(scanf("%d",&num)){
				if(!num)break;
				mp[i][num]=1;
			}
		}

		dp[0][0]=1;
		groupcnt=0;
		for(int i=1;i<=n;i++){
			if(lv[i]==-1){
				lv[i]=0;
				groupcnt++;
				tmp=0;
				dfs(i);
				//cout<<i<<" "<<tmp<<endl;

				for(int j=0;j<=n/2;j++){
					if(dp[groupcnt-1][j]){
						if(j+tmp>=0){
							dp[groupcnt][j+tmp]=1;
							pre[groupcnt][j+tmp]=j;
						}
						if(j-tmp>=0){
							dp[groupcnt][j-tmp]=1;
							pre[groupcnt][j-tmp]=j;
						}
					}
				}
			}
		}

		int ans=0;
		for(int i=0;i<=n;i++){
			if(dp[groupcnt][i]){
				ans=i;break;
			}
		}

		bool ok=1;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(i==j)continue;
				if( !(mp[i][j]&&mp[j][i]) ){
					if(lv[i]==lv[j]){
						ok=0;
					}
				}
			}
		}

		if(ok){
			//cout<<ans<<endl;
			int cur=ans;
			vector<int> ans0;
			vector<int> ans1;
			for(int i=groupcnt;i>=1;i--){
				int p=pre[i][cur];

				vector<int> &big=s0[i];
				vector<int> &small=s1[i];
				if(big.size()<small.size()){
					swap(big,small);
				}

				//cout<<"????size"<<big.size()<<" ��????size"<<small.size()<<endl;

				if(p<cur)swap(big,small);

				for(int j=0;j<big.size();j++){
					ans0.push_back(big[j]);
				}
				for(int j=0;j<small.size();j++){
					ans1.push_back(small[j]);
				}

				cur=p;
			}
			cout<<ans0.size()<<" ";
			for(int i=0;i<ans0.size();i++){
				cout<<ans0[i]<<" ";
			}cout<<endl;
			cout<<ans1.size()<<" ";
			for(int i=0;i<ans1.size();i++){
				cout<<ans1[i]<<" ";
			}cout<<endl;
		}else{
			cout<<"No solution"<<endl;
		}
		//if(t)cout<<endl;
	}
	return 0;
}*/


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

#define ll long long
const int INF = 1e9;

ll gcd(ll a,ll b){
	return b==0?a:gcd(b,a%b);
}

int main(){

	ll m,h1,a1,x1,y1;
	ll   h2,a2,x2,y2;
	cin>>m;
	cin>>h1>>a1;
	cin>>x1>>y1;
	cin>>h2>>a2;
	cin>>x2>>y2;

	//
	ll ans1=1;
	for(;ans1<=m*2;ans1++){
		h1=x1*h1+y1;
		h1%=m;
		if(h1==a1)break;
	}

	ll ans2=1;
	for(;ans2<=m*2;ans2++){
		h2=x2*h2+y2;
		h2%=m;
		if(h2==a2)break;
	}

	bool ok=1;
	if(ans1>m*2||ans2>m*2)ok=0;

	if(ok){
		//ll ans=ans1*ans2/gcd(ans1,ans2);
		//cout<<ans;
		cout<<max(ans1,ans2);
	}else{
		cout<<"-1";
	}

	return 0;
}

/*
#define ll long long
const int INF=1e9;

int mp[110][110];
int lv[110];
bool dp[110][110];
int n;
vector<int> s0[110];
vector<int> s1[110];
int groupcnt;
int pre[110][110];

int re;
int tmp;
void dfs(int u){
//	cout<<"dfsing "<<u<<endl;
	if(lv[u]){
		s0[groupcnt].push_back(u);
		tmp--;
	}else{
		s1[groupcnt].push_back(u);
		tmp++;
	}
	for(int v=1;v<=n;v++){
		if(v==u)continue;
		if(!(mp[u][v]&&mp[v][u])){
			if(lv[v]!=-1){
				if((lv[v]&1)==(lv[u]&1)){
					return;
				}else{
					continue;
				}
			}
			lv[v]=!lv[u];
			dfs(v);
		}
	}
}

void init(){
	memset(mp,0,sizeof(mp));
	memset(lv,-1,sizeof(lv));
	memset(dp,0,sizeof(dp));
	memset(s0,0,sizeof(s0));
	memset(s1,0,sizeof(s1));
}

int main(){
	//int t;
	//cin>>t;
	while(cin>>n){

		init();

		//cin>>n;
		for(int i=1;i<=n;i++){
			int num;
			while(scanf("%d",&num)){
				if(!num)break;
				mp[i][num]=1;
			}
		}

		dp[0][0]=1;
		groupcnt=0;
		for(int i=1;i<=n;i++){
			if(lv[i]==-1){
				lv[i]=0;
				groupcnt++;
				tmp=0;
				dfs(i);
				//cout<<i<<" "<<tmp<<endl;

				for(int j=0;j<=n/2;j++){
					if(dp[groupcnt-1][j]){
						if(j+tmp>=0){
							dp[groupcnt][j+tmp]=1;
							pre[groupcnt][j+tmp]=j;
						}
						if(j-tmp>=0){
							dp[groupcnt][j-tmp]=1;
							pre[groupcnt][j-tmp]=j;
						}
					}
				}
			}
		}

		int ans=0;
		for(int i=0;i<=n;i++){
			if(dp[groupcnt][i]){
				ans=i;break;
			}
		}

		bool ok=1;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(i==j)continue;
				if( !(mp[i][j]&&mp[j][i]) ){
					if(lv[i]==lv[j]){
						ok=0;
					}
				}
			}
		}

		if(ok){
			//cout<<ans<<endl;
			int cur=ans;
			vector<int> ans0;
			vector<int> ans1;
			for(int i=groupcnt;i>=1;i--){
				int p=pre[i][cur];

				vector<int> &big=s0[i];
				vector<int> &small=s1[i];
				if(big.size()<small.size()){
					swap(big,small);
				}

				//cout<<"�󼯺�size"<<big.size()<<" С����size"<<small.size()<<endl;

				if(p<cur)swap(big,small);

				for(int j=0;j<big.size();j++){
					ans0.push_back(big[j]);
				}
				for(int j=0;j<small.size();j++){
					ans1.push_back(small[j]);
				}

				cur=p;
			}
			cout<<ans0.size()<<" ";
			for(int i=0;i<ans0.size();i++){
				cout<<ans0[i]<<" ";
			}cout<<endl;
			cout<<ans1.size()<<" ";
			for(int i=0;i<ans1.size();i++){
				cout<<ans1[i]<<" ";
			}cout<<endl;
		}else{
			cout<<"No solution"<<endl;
		}
		//if(t)cout<<endl;
	}
	return 0;
}*/


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

#define ll long long
const int INF = 1e9;

ll gcd(ll a,ll b){
	if(b==0)return a;
	return gcd(b,a%b);
}

ll MIN(ll a,ll b){
	if(a>b)return b;
	return a;
}

set<ll> s1;
set<ll> s2;

int main(){

	ll m,h1,a1,x1,y1;
	ll   h2,a2,x2,y2;
	cin>>m;
	cin>>h1>>a1;
	cin>>x1>>y1;
	cin>>h2>>a2;
	cin>>x2>>y2;

	//
	ll ans1=1;
	for(;ans1<=m*2;ans1++){
		h1=x1*h1+y1;
		h1%=m;
		if(h1==a1){
			s1.insert(ans1);
		}
	}

	ll ans2=1;
	for(;ans2<=m*2;ans2++){
		h2=x2*h2+y2;
		h2%=m;
		if(h2==a2){
			s2.insert(ans2);
		}
	}

	bool ok=1;
	if(s1.empty()||s2.empty())ok=0;

	if(ok){
		ll ans=110000000000000LL;

		for(set<ll>::iterator it1=s1.begin();it1!=s1.end();it1++){
			if(*it1>ans)break;
			for(set<ll>::iterator it2=s2.begin();it2!=s2.end();it2++){
				if(*it2>ans)break;
				ll t1=*it1,	t2=*it2;
				ans=MIN(ans, t1*t2/gcd(t1,t2) );
			}
		}

		//ans1*ans2/gcd(ans1,ans2);
		cout<<ans;

	}else{
		cout<<"-1";
	}

	return 0;
}

/*
#define ll long long
const int INF=1e9;

int mp[110][110];
int lv[110];
bool dp[110][110];
int n;
vector<int> s0[110];
vector<int> s1[110];
int groupcnt;
int pre[110][110];

int re;
int tmp;
void dfs(int u){
//	cout<<"dfsing "<<u<<endl;
	if(lv[u]){
		s0[groupcnt].push_back(u);
		tmp--;
	}else{
		s1[groupcnt].push_back(u);
		tmp++;
	}
	for(int v=1;v<=n;v++){
		if(v==u)continue;
		if(!(mp[u][v]&&mp[v][u])){
			if(lv[v]!=-1){
				if((lv[v]&1)==(lv[u]&1)){
					return;
				}else{
					continue;
				}
			}
			lv[v]=!lv[u];
			dfs(v);
		}
	}
}

void init(){
	memset(mp,0,sizeof(mp));
	memset(lv,-1,sizeof(lv));
	memset(dp,0,sizeof(dp));
	memset(s0,0,sizeof(s0));
	memset(s1,0,sizeof(s1));
}

int main(){
	//int t;
	//cin>>t;
	while(cin>>n){

		init();

		//cin>>n;
		for(int i=1;i<=n;i++){
			int num;
			while(scanf("%d",&num)){
				if(!num)break;
				mp[i][num]=1;
			}
		}

		dp[0][0]=1;
		groupcnt=0;
		for(int i=1;i<=n;i++){
			if(lv[i]==-1){
				lv[i]=0;
				groupcnt++;
				tmp=0;
				dfs(i);
				//cout<<i<<" "<<tmp<<endl;

				for(int j=0;j<=n/2;j++){
					if(dp[groupcnt-1][j]){
						if(j+tmp>=0){
							dp[groupcnt][j+tmp]=1;
							pre[groupcnt][j+tmp]=j;
						}
						if(j-tmp>=0){
							dp[groupcnt][j-tmp]=1;
							pre[groupcnt][j-tmp]=j;
						}
					}
				}
			}
		}

		int ans=0;
		for(int i=0;i<=n;i++){
			if(dp[groupcnt][i]){
				ans=i;break;
			}
		}

		bool ok=1;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(i==j)continue;
				if( !(mp[i][j]&&mp[j][i]) ){
					if(lv[i]==lv[j]){
						ok=0;
					}
				}
			}
		}

		if(ok){
			//cout<<ans<<endl;
			int cur=ans;
			vector<int> ans0;
			vector<int> ans1;
			for(int i=groupcnt;i>=1;i--){
				int p=pre[i][cur];

				vector<int> &big=s0[i];
				vector<int> &small=s1[i];
				if(big.size()<small.size()){
					swap(big,small);
				}

				//cout<<"????size"<<big.size()<<" ��????size"<<small.size()<<endl;

				if(p<cur)swap(big,small);

				for(int j=0;j<big.size();j++){
					ans0.push_back(big[j]);
				}
				for(int j=0;j<small.size();j++){
					ans1.push_back(small[j]);
				}

				cur=p;
			}
			cout<<ans0.size()<<" ";
			for(int i=0;i<ans0.size();i++){
				cout<<ans0[i]<<" ";
			}cout<<endl;
			cout<<ans1.size()<<" ";
			for(int i=0;i<ans1.size();i++){
				cout<<ans1[i]<<" ";
			}cout<<endl;
		}else{
			cout<<"No solution"<<endl;
		}
		//if(t)cout<<endl;
	}
	return 0;
}*/


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

#define ll long long
const int INF = 1e9;

ll gcd(ll a,ll b){
	if(b==0)return a;
	return gcd(b,a%b);
}

ll MIN(ll a,ll b){
	if(a>b)return b;
	return a;
}

set<ll> s1;
set<ll> s2;

int main(){

	ll m,h1,a1,x1,y1;
	ll   h2,a2,x2,y2;
	cin>>m;
	cin>>h1>>a1;
	cin>>x1>>y1;
	cin>>h2>>a2;
	cin>>x2>>y2;

	//
	ll ans1=1;
	for(;ans1<=m+10;ans1++){
		h1=x1*h1+y1;
		h1%=m;
		if(h1==a1){
			s1.insert(ans1);
		}
	}

	ll ans2=1;
	for(;ans2<=m+10;ans2++){
		h2=x2*h2+y2;
		h2%=m;
		if(h2==a2){
			s2.insert(ans2);
		}
	}

	bool ok=1;
	if(s1.empty()||s2.empty())ok=0;

	if(ok){
		ll ans=110000000000000LL;

		for(set<ll>::iterator it1=s1.begin();it1!=s1.end();it1++){
			//if(*it1>ans)break;
			for(set<ll>::iterator it2=s2.begin();it2!=s2.end();it2++){
			//	if(*it2>ans)break;
				ll t1=*it1,	t2=*it2;
				ans=MIN(ans, t1*t2/gcd(t1,t2) );
			}
		}

		//ans1*ans2/gcd(ans1,ans2);
		cout<<ans;

	}else{
		cout<<"-1";
	}

	return 0;
}

/*
#define ll long long
const int INF=1e9;

int mp[110][110];
int lv[110];
bool dp[110][110];
int n;
vector<int> s0[110];
vector<int> s1[110];
int groupcnt;
int pre[110][110];

int re;
int tmp;
void dfs(int u){
//	cout<<"dfsing "<<u<<endl;
	if(lv[u]){
		s0[groupcnt].push_back(u);
		tmp--;
	}else{
		s1[groupcnt].push_back(u);
		tmp++;
	}
	for(int v=1;v<=n;v++){
		if(v==u)continue;
		if(!(mp[u][v]&&mp[v][u])){
			if(lv[v]!=-1){
				if((lv[v]&1)==(lv[u]&1)){
					return;
				}else{
					continue;
				}
			}
			lv[v]=!lv[u];
			dfs(v);
		}
	}
}

void init(){
	memset(mp,0,sizeof(mp));
	memset(lv,-1,sizeof(lv));
	memset(dp,0,sizeof(dp));
	memset(s0,0,sizeof(s0));
	memset(s1,0,sizeof(s1));
}

int main(){
	//int t;
	//cin>>t;
	while(cin>>n){

		init();

		//cin>>n;
		for(int i=1;i<=n;i++){
			int num;
			while(scanf("%d",&num)){
				if(!num)break;
				mp[i][num]=1;
			}
		}

		dp[0][0]=1;
		groupcnt=0;
		for(int i=1;i<=n;i++){
			if(lv[i]==-1){
				lv[i]=0;
				groupcnt++;
				tmp=0;
				dfs(i);
				//cout<<i<<" "<<tmp<<endl;

				for(int j=0;j<=n/2;j++){
					if(dp[groupcnt-1][j]){
						if(j+tmp>=0){
							dp[groupcnt][j+tmp]=1;
							pre[groupcnt][j+tmp]=j;
						}
						if(j-tmp>=0){
							dp[groupcnt][j-tmp]=1;
							pre[groupcnt][j-tmp]=j;
						}
					}
				}
			}
		}

		int ans=0;
		for(int i=0;i<=n;i++){
			if(dp[groupcnt][i]){
				ans=i;break;
			}
		}

		bool ok=1;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(i==j)continue;
				if( !(mp[i][j]&&mp[j][i]) ){
					if(lv[i]==lv[j]){
						ok=0;
					}
				}
			}
		}

		if(ok){
			//cout<<ans<<endl;
			int cur=ans;
			vector<int> ans0;
			vector<int> ans1;
			for(int i=groupcnt;i>=1;i--){
				int p=pre[i][cur];

				vector<int> &big=s0[i];
				vector<int> &small=s1[i];
				if(big.size()<small.size()){
					swap(big,small);
				}

				//cout<<"????size"<<big.size()<<" ��????size"<<small.size()<<endl;

				if(p<cur)swap(big,small);

				for(int j=0;j<big.size();j++){
					ans0.push_back(big[j]);
				}
				for(int j=0;j<small.size();j++){
					ans1.push_back(small[j]);
				}

				cur=p;
			}
			cout<<ans0.size()<<" ";
			for(int i=0;i<ans0.size();i++){
				cout<<ans0[i]<<" ";
			}cout<<endl;
			cout<<ans1.size()<<" ";
			for(int i=0;i<ans1.size();i++){
				cout<<ans1[i]<<" ";
			}cout<<endl;
		}else{
			cout<<"No solution"<<endl;
		}
		//if(t)cout<<endl;
	}
	return 0;
}*/


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <set>
#include <stdlib.h>
using namespace std;
int m,h1,a1,x1,y1,h2,a2,x2,y2;
long long f;
long long ans;
int main(){
    freopen("A.inp","r",stdin);
    scanf("%d",&m);
    scanf("%d%d",&h1,&a1);
    scanf("%d%d",&x1,&y1);
    scanf("%d%d",&h2,&a2);
    scanf("%d%d",&x2,&y2);
    int t1=0,t2=0;
    int vtd=0,vtc=0;
    f=h1;
    for (int i=1;i<=2*m;i++){
        f=(1LL*x1*1LL*f+y1)%m;
        if (f==a1) if (vtd==0) vtd=i; else vtc=i;
    }
    if (vtd==0 || vtc==0){
        printf("-1");
        return 0;
    }
    t1=vtd;
    int r1=vtc-vtd;
    vtd=0; vtc=0;
    f=h2;
    for (int i=1;i<=2*m;i++){
        f=(1LL*x2*1LL*f+y2)%m;
        if (f==a2) if (vtd==0) vtd=i; else vtc=i;
    }
    if (vtd==0 || vtc==0){
        printf("-1");
        return 0;
    }
    t2=vtd;
    int r2=vtc-vtd;
    //cout<<t1<<" "<<r1<<" "<<t2<<" "<<r2<<endl;
    ans=-1;
    for (int k1=0;k1<=3000000;k1++){
        if ((1LL*k1*1LL*r1+t1-t2)%r2==0){
            ans=1LL*k1*1LL*r1+t1;
            break;
        }
    }
    cout<<ans;
}


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <set>
#include <stdlib.h>
using namespace std;
int m,h1,a1,x1,y1,h2,a2,x2,y2;
long long f;
long long ans;
int main(){
    scanf("%d",&m);
    scanf("%d%d",&h1,&a1);
    scanf("%d%d",&x1,&y1);
    scanf("%d%d",&h2,&a2);
    scanf("%d%d",&x2,&y2);
    int t1=0,t2=0;
    int vtd=0,vtc=0;
    f=h1;
    for (int i=1;i<=3*m;i++){
        f=(1LL*x1*1LL*f+y1)%m;
        if (f==a1) {if (vtd==0) vtd=i; else vtc=i;}
    }
    if (vtd==0 || vtc==0){
        printf("-1");
        return 0;
    }
    t1=vtd;
    int r1=vtc-vtd;
    vtd=0; vtc=0;
    f=h2;
    for (int i=1;i<=3*m;i++){
        f=(1LL*x2*1LL*f+y2)%m;
        if (f==a2) {if (vtd==0) vtd=i; else vtc=i;}
    }
    if (vtd==0 || vtc==0){
        printf("-1");
        return 0;
    }
    t2=vtd;
    int r2=vtc-vtd;
    //cout<<t1<<" "<<r1<<" "<<t2<<" "<<r2<<endl;
    ans=-1;
    for (int k1=0;k1<=1000000;k1++){
        if ((1LL*k1*1LL*r1+t1-t2)%r2==0 && 1LL*k1*1LL*r1+t1-t2>=0){
            ans=1LL*k1*1LL*r1+t1;
            break;
        }
    }
    cout<<ans;
}


#from sys import stdin,stdout
#import operator
#from collections import OrderedDict
#def getKey(item):
#     return item[0]
n,k=map(int,input().strip().split(" "))
#n,k=map(int,stdin.readline().rstrip().split(" "))
lst=list(map(int,input().strip().split(" ")))
#lst=list(map(int,stdin.readline().rstrip().split()))
s=input()
#s=stdin.readline()
#l=[0]*n
#for i in range(n):
#    l[i]=[lst[i],s[i]]

#l=sorted(l, key=getKey,reverse=True)
ss=0
s+=' '
num=[]
sss=0
i=0
while i<n:
    cnt=0
    sss=0
    if s[i]==s[i+1]:
        for j in range(i,n):
            num.append(lst[j])
            cnt+=1
            sss+=lst[j]
            if s[j]!=s[j+1]:
                break
        i+=cnt
        if cnt<=k:
            ss+=sss
        else:
            num.sort(reverse=True)
            for j in range(k):
                ss+=num[j]

        num=[]
    else:
        ss+=lst[i]
        i+=1

print(ss)


from sys import stdin,stdout
#import operator
#from collections import OrderedDict
#def getKey(item):
#     return item[0]
#n,k=map(int,input().strip().split(" "))
n,k=map(int,stdin.readline().rstrip().split(" "))
#lst=list(map(int,input().strip().split(" ")))
lst=list(map(int,stdin.readline().rstrip().split()))
#s=input()
s=stdin.readline()
#l=[0]*n
#for i in range(n):
#    l[i]=[lst[i],s[i]]

#l=sorted(l, key=getKey,reverse=True)
ss=0
s+=' '
num=[]
sss=0
i=0
while i<n:
    cnt=0
    sss=0
    if s[i]==s[i+1]:
        for j in range(i,n):
            num.append(lst[j])
            cnt+=1
            sss+=lst[j]
            if s[j]!=s[j+1]:
                break
        i+=cnt
        if cnt<=k:
            ss+=sss
        else:
            num.sort(reverse=True)
            for j in range(k):
                ss+=num[j]

        num=[]
    else:
        ss+=lst[i]
        i+=1

print(ss)


n,k=map(int,input().split())
a=list(map(int,input().split()))
s=str(input())
ans=0
i=0
b=[]
while(i<n):
    b.append(a[i])
    if(i+1>=n or (i+1<n and s[i+1]!=s[i])):
        b.sort()
        b.reverse()
        p=0
        i+=1
        while(p<len(b) and p<k):
            ans+=b[p]
            p+=1
        b=[]
        continue
    i+=1
print(ans)


n, k = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
buttons = input()
dmg = 0
i = 0
while i < n:
    subset = []
    subset.append(arr[i])
    j = i + 1
    if j >= len(arr):
        dmg += arr[i]
        break
    consec = 1
    currTot = 0
    currTot += arr[i]
    while j < n and buttons[j] == buttons[i]:
        consec += 1
        currTot += arr[j]
        subset.append(arr[j])
        j += 1
    if consec <= k:
        dmg += currTot
    else:
        subset.sort(reverse=True)
        dmg += sum(subset[:(k)])
    i = j
print(dmg)


n, k = map(int, input().split())
a = [int(x) for x in input().split()]
a.append(-1)
dmg = 0
d = {}
s = input() + '#'

for i in range(n + 1):
    if s[i] not in d:
        d[s[i]] = [a[i]]
    if s[i] in d and i > 0 and s[i-1] != s[i]:
        dmg += sum(sorted(d.pop(s[i-1]))[-k:])
    elif s[i] in d and i > 0 and s[i-1] == s[i]:
        d[s[i]].append(a[i])
print(dmg)


n, k = map(int, input().split())
a = [int(x) for x in input().split()]
dmg = 0
combo = 0
button = ''
s = input()

for i in range(n):
    if button == '': button = s[i]
    if s[i] != button or i == n - 1:
        if i != n - 1: sequence = a[combo:i]
        else: sequence = a[combo:]
        sequence.sort(reverse = True)
        dmg += sum(sequence[:k])
        button = s[i]
        combo = i
print(dmg)


n, k = map(int, input().split())
l = list(map(int, input().split()))
slist = input()
l_tmp = []
dmg = 0

def remv(slist, l):
    l_tmp = []
    s= slist[0]
    #print(s, slist, s==slist[0])
    for i in range(len(l)):
        if(s==slist[0]):
            #print(slist[0], s==slist[0], l)
            slist = slist[1:]
            l_tmp.append(l.pop(0))
        else:
            l_tmp.sort()
            return l, l_tmp, slist
    l_tmp.sort()
    return l, l_tmp, slist

while len(l)>0:
    l, l_tmp, slist = remv(slist, l)
    l_tmp.sort()
    for i in range(min(len(l_tmp), k)): dmg += l_tmp.pop()
    #print(l, l_tmp, slist, dmg)
print(dmg)


n, k = map(int, input().split())
l = list(map(int, input().split()))
slist = input()
l_tmp = []
dmg = 0

def remv(slist, l):
    l_tmp = []
    s= slist[0]
    #print(s, slist, s==slist[0])
    for i in range(len(l)):
        if(s==slist[0]):
            #print(slist[0], s==slist[0], l)
            slist = slist[1:]
            l_tmp.append(l.pop(0))
        else:
            l_tmp.sort()
            return l, l_tmp, slist
    l_tmp.sort()
    return l, l_tmp, slist

while len(l)>0:
    l, l_tmp, slist = remv(slist, l)
    l_tmp.sort()
    for i in range(min(len(l_tmp), k)): dmg += l_tmp.pop()
    #print(l, l_tmp, slist, dmg)
    print(dmg)


n, k = map(int, input().split())
l = list(map(int, input().split()))
slist = list(input())
dmg = 0
i=0
while i<n:
    j = i+1
    count = 1
    l_tmp = [l[i]]
    while j<n and slist[i] == slist[j]:
        count += 1
        l_tmp.append(l[j])
        j+=1
    l_tmp.sort(reverse = True)
    dmg += sum(l_tmp[:min(count, k)])
    i = j
print(dmg)


n, k = map(int, input().split())
l = list(map(int, input().split()))
slist = list(input())
l_tmp = []
dmg = 0

while len(l)>0:
    l_tmp = []
    s= slist[0]
    #print(s, l)
    for i in range(len(l)):
        if(s==slist[0]):
            slist.pop(0)
            l_tmp.append(l.pop(0))
        else:
            break
    l_tmp.sort()
    for i in range(min(len(l_tmp), k)): dmg += l_tmp.pop()
print(dmg)


n,b=input().split()
n=int(n)
b=int(b)
j=0
lt=[]
tempLt=[]
lt=list(map(int,input().split()))
str=input()
for i in range(len(str)):
    if i==0:
        tempLt.append(lt[i])
        j=0
    elif str[i]==str[i-1]:
        tempLt.append(lt[i])
    else:
        tempLt.sort()
        tempLt.reverse()
        for k in range(j,i):
            lt[k]=tempLt[k-j]
        del tempLt
        tempLt=[]
        5
        tempLt.append(lt[i])
        j=i
tempLt.sort()
tempLt.reverse()
for k in range(j,i+1):
    lt[k]=tempLt[k-j]
dmg=lt[0]
counter=1
for i in range(1,len(str)):
    if str[i]==str[i-1]:
        if counter<b:
            counter+=1
            dmg+=lt[i]
    else:
        counter=1
        dmg+=lt[i]
print(dmg)


n,b=input().split()
n=int(n)
b=int(b)
j=0
lt=[]
tempLt=[]
lt=list(map(int,input().split()))
str=input()
for i in range(len(str)):
    if i==0:
        tempLt.append(lt[i])
        j=0
    elif str[i]==str[i-1]:
        tempLt.append(lt[i])
    else:
        tempLt.sort()
        tempLt.reverse()
        for k in range(j,i):
            lt[k]=tempLt[k-j]
        del tempLt
        tempLt=[]
        5
        tempLt.append(lt[i])
        j=i
tempLt.sort()
tempLt.reverse()
for k in range(j,i+1):
    lt[k]=tempLt[k-j]
dmg=lt[0]
counter=1
print(lt)
for i in range(1,len(str)):
    if str[i]==str[i-1]:
        if counter<b:
            counter+=1
            dmg+=lt[i]
    else:
        counter=1
        dmg+=lt[i]
print(dmg)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
sum_ = 0
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        #print(counter)
        if counter == len(string) - 1:
            #left = i  + 1 - counter
            #right = i + 1
            #print(left,right)
            #new_array = array[left:right + 1]
            #print(new_array)
            sorted_array = sorted(array)
            #print(sorted_array)
            #print(sorted_array[len(sorted_array) - k])
            sum_ += sum(sorted_array[len(sorted_array) - min(len(sorted_array),k):])
            #print(sum(sorted_array[len(sorted_array) - min(k,len(sorted_array)):]))
            counter = 0
            print(sum_)
            sys.exit(0)
    elif string[i] != string[i + 1] and counter >= k:
        left = i - counter
        right = i
        #print(i,i - k)
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        #print(sorted_array)
        #print(sorted_array[len(sorted_array) - k])
        sum_ += sum(sorted_array[len(sorted_array) - k:])
        #print(sum(sorted_array[len(sorted_array) - counter:]))
        counter = 0
    else:
        sum_ += array[i]
        #print(array[i])
if counter >= k:
    left = len(string) - 1 - counter
    right = len(string) - 1
    #print(i,i - k)
    new_array = array[left:right + 1]
    #print(new_array)
    sorted_array = sorted(new_array)
    #print(sorted_array)
    #print(sorted_array[len(sorted_array) - counter:])
    sum_ += sum(sorted_array[len(sorted_array) - k:])
    #print(sum(sorted_array[len(sorted_array) - k:]))
else:
    sum_ += array[len(string) - 1]
    #print(array[len(string) - 1])
print(sum_)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
sum_ = 0
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        #print(counter)
        if counter == len(string) - 1:
            #left = i  + 1 - counter
            #right = i + 1
            #print(left,right)
            #new_array = array[left:right + 1]
            #print(new_array)
            sorted_array = sorted(array)
            #print(sorted_array)
            #print(sorted_array[len(sorted_array) - k])
            sum_ += sum(sorted_array[len(sorted_array) - k:])
            #print(sum(sorted_array[len(sorted_array) - min(k,len(sorted_array)):]))
            counter = 0
            print(sum_)
            sys.exit(0)
    elif string[i] != string[i + 1] and counter >= k:
        left = i - counter
        right = i
        #print(i,i - k)
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        #print(sorted_array)
        #print(sorted_array[len(sorted_array) - k])
        sum_ += sum(sorted_array[len(sorted_array) - k:])
        #print(sum(sorted_array[len(sorted_array) - counter:]))
        counter = 0
    else:
        sum_ += array[i]
        #print(array[i])
if counter >= k:
    left = len(string) - 1 - counter
    right = len(string) - 1
    #print(i,i - k)
    new_array = array[left:right + 1]
    #print(new_array)
    sorted_array = sorted(new_array)
    #print(sorted_array)
    #print(sorted_array[len(sorted_array) - counter:])
    sum_ += sum(sorted_array[len(sorted_array) - k:])
    #print(sum(sorted_array[len(sorted_array) - k:]))
else:
    sum_ += array[len(string) - 1]
    #print(array[len(string) - 1])
print(sum_)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
sum_ = 0
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        #print(counter)
        if counter == len(string) - 1:
            #left = i  + 1 - counter
            #right = i + 1
            #print(left,right)
            #new_array = array[left:right + 1]
            #print(new_array)
            sorted_array = sorted(array)
            #print(sorted_array)
            #print(sorted_array[len(sorted_array) - k])
            sum_ += sum(sorted_array[len(sorted_array) - min(len(sorted_array),k):])
            #print(sum(sorted_array[len(sorted_array) - min(k,len(sorted_array)):]))
            counter = 0
            print(sum_)
            sys.exit(0)
    elif string[i] != string[i + 1] and counter >= k:
        left = i - counter
        right = i
        #print(i,i - k)
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        #print(sorted_array)
        #print(sorted_array[len(sorted_array) - k])
        sum_ += sum(sorted_array[len(sorted_array) - counter:])
        #print(sum(sorted_array[len(sorted_array) - counter:]))
        counter = 0
    else:
        sum_ += array[i]
        #print(array[i])
if string[len(string) - 1] == string[len(string) - 2] and counter >= k:
    left = len(string) - 1 - counter
    right = len(string) - 1
    #print(i,i - k)
    new_array = array[left:right + 1]
    #print(new_array)
    sorted_array = sorted(new_array)
    #print(sorted_array)
    #print(sorted_array[len(sorted_array) - counter:])
    sum_ += sum(sorted_array[len(sorted_array) - k:])
    #print(sum(sorted_array[len(sorted_array) - k:]))
else:
    sum_ += array[len(string) - 1]
    #print(array[len(string) - 1])
print(sum_)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
extra = []
sum_ = 0
if len(string) == 1:
    print(array[0])
    sys.exit(0)
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        right = i + 1
        #print(counter)
        if i + 2 == len(string):
            left = i + 1 - counter
          #  print(left)
            new_array = array[left:right + 1]
         #   print(new_array)
            sorted_array = sorted(new_array)
            sum_ += sum(sorted_array[len(sorted_array) - min(k,counter + 1):])
            counter = 0
    elif string[i] != string[i + 1]: #and counter >= k:
        left = i - counter
        right = i
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        sum_ += sum(sorted_array[len(sorted_array) - min(k,counter + 1):])
        counter = 0
if string[len(string) - 1] != string[len(string) - 2]:
    sum_ += array[len(string) - 1]
print(sum_)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
extra = []
sum_ = 0
if len(string) == 1:
    print(string)
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        right = i + 1
        #print(counter)
        if i + 2 == len(string):
            left = i + 1 - counter
          #  print(left)
            new_array = array[left:right + 1]
         #   print(new_array)
            sorted_array = sorted(new_array)
            sum_ += sum(sorted_array[len(sorted_array) - min(k,counter + 1):])
            counter = 0
    elif string[i] != string[i + 1]: #and counter >= k:
        left = i - counter
        right = i
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        sum_ += sum(sorted_array[len(sorted_array) - min(k,counter + 1):])
        counter = 0
if string[len(string) - 1] != string[len(string) - 2]:
    sum_ += array[len(string) - 1]
print(sum_)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
sum_ = 0
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        #print(counter)
        if counter == len(string) - 1:
            #left = i  + 1 - counter
            #right = i + 1
            #print(left,right)
            #new_array = array[left:right + 1]
            #print(new_array)
            sorted_array = sorted(array)
            #print(sorted_array)
            #print(sorted_array[len(sorted_array) - k])
            sum_ += sum(sorted_array[len(sorted_array) - min(len(sorted_array),k):])
            #print(sum(sorted_array[len(sorted_array) - min(k,len(sorted_array)):]))
            counter = 0
            print(sum_)
            sys.exit(0)
    elif string[i] != string[i + 1] and counter >= k:
        left = i - k
        right = i
        #print(i,i - k)
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        #print(sorted_array)
        #print(sorted_array[len(sorted_array) - k])
        sum_ += sum(sorted_array[len(sorted_array) - counter:])
        #print(sum(sorted_array[len(sorted_array) - k:]))
        counter = 0
    else:
        sum_ += array[i]
        #print(array[i])
if string[len(string) - 1] == string[len(string) - 2] and counter >= k:
    left = len(string) - 1 - k
    right = len(string) - 1
    #print(i,i - k)
    new_array = array[left:right + 1]
    #print(new_array)
    sorted_array = sorted(new_array)
    #print(sorted_array)
    #print(sorted_array[len(sorted_array) - k])
    sum_ += sum(sorted_array[len(sorted_array) - counter:])
    #print(sum(sorted_array[len(sorted_array) - k:]))
else:
    sum_ += array[len(string) - 1]
    #print(array[len(string) - 1])
print(sum_)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
extra = []
sum_ = 0
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        right = i + 1
        #print(counter)
        if i + 2 == len(string):
            left = i + 1 - counter
          #  print(left)
            new_array = array[left:right + 1]
         #   print(new_array)
            sorted_array = sorted(new_array)
            sum_ += sum(sorted_array[len(sorted_array) - min(k,counter + 1):])
            counter = 0
    elif string[i] != string[i + 1]: #and counter >= k:
        left = i - counter
        right = i
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        sum_ += sum(sorted_array[len(sorted_array) - min(k,counter + 1):])
        counter = 0
if string[len(string) - 1] != string[len(string) - 2]:
    sum_ += array[len(string) - 1]
print(sum_)


import sys
n, k = [int(s) for s in input().split()]
array = [int(s) for s in input().split()]
string = input()
counter = 0
sum_ = 0
for i in range(len(string) - 1):
    if string[i] == string[i + 1]:
        counter += 1
        #print(counter)
        if counter == len(string) - 1:
            left = i  + 1 - counter
            right = i + 1
            #print(left,right)
            new_array = array[left:right + 1]
            #print(new_array)
            sorted_array = sorted(new_array)
            #print(sorted_array)
            #print(sorted_array[len(sorted_array) - k])
            sum_ += sum(sorted_array[len(sorted_array) - min(len(sorted_array),k):])
            #print(sum(sorted_array[len(sorted_array) - min(k,len(sorted_array)):]))
            counter = 0
            print(sum_)
            sys.exit(0)
    elif string[i] != string[i + 1] and counter >= k:
        left = i - k
        right = i
        #print(i,i - k)
        new_array = array[left:right + 1]
        #print(new_array)
        sorted_array = sorted(new_array)
        #print(sorted_array)
        #print(sorted_array[len(sorted_array) - k])
        sum_ += sum(sorted_array[len(sorted_array) - min(len(sorted_array),k):])
        #print(sum(sorted_array[len(sorted_array) - k:]))
        counter = 0
    else:
        sum_ += array[i]
        #print(array[i])
if string[len(string) - 1] == string[len(string) - 2] and counter >= k:
    left = len(string) - 1 - k
    right = len(string) - 1
    #print(i,i - k)
    new_array = array[left:right + 1]
    #print(new_array)
    sorted_array = sorted(new_array)
    #print(sorted_array)
    #print(sorted_array[len(sorted_array) - k])
    sum_ += sum(sorted_array[len(sorted_array) - min(len(sorted_array),k):])
    #print(sum(sorted_array[len(sorted_array) - k:]))
else:
    sum_ += array[len(string) - 1]
    #print(array[len(string) - 1])
print(sum_)


k=[int(e) for e in input().split()]
l1=[int(e) for e in input().split()]
s=input()
l=[[l1[0]]]
for i in range(1,k[0]):
    if s[i]==s[i-1]:
        l[-1].append(l1[i])
    else:
        l.append([l1[i]])
sm=0
for i in l:
    if len(i)<=k[1]:
        sm+=sum(i)
    else:
        i.sort(reverse=True)
        sm+=sum(i[:k[1]])
print(sm)


n,k = map(int,input().split())
arr = list(map(int,input().split()))
string = input()

if n == 1 or n < k:
    print(sum(arr))
    exit()
i,j = 0,1
sums,add = [0]*n,0
sums[0],ans = arr[0],0
while(j < n):
    if string[i] == string[j]:
        while(j < n and string[i] == string[j] ):
            j += 1
        if string[i] == string[j-1]:
            modi = sorted(arr[i:j])
            #print(k)
            #print(modi,len(modi),len(modi)-k)
            if j-i > k:
                ans += sum(modi[len(modi)-k:])
            else:
                ans += sum(modi)
            i = j
            j += 1
    else:
        ans += arr[i]
        i = j
        j += 1
if i < n:
    ans += arr[i]
print(ans)


n,k=map(int,input().split())
a=list(map(int,input().split()))
s=input()
c=1
d=[]
x=s[0]
for i in range(1,len(s)):
    if(x==s[i]):
        c=c+1
    else:
        if(c>k):
            #print(i,c)
            t=a[i-c:i]
            t.sort()
            #print(i-c+1,i+1)
            d+=(t[:c-k])
        c=1
        x=s[i]
if(c>k):
    t=a[i-c+1:i+1]
    t.sort()
    #print(i-c+1,i+1)
    d+=(t[:c-k])
#print(a,d)
print(sum(a)-sum(d))


#!/usr/bin/python

if __name__ == "__main__":
    n , k = map(int, input().split())
    string_a = input().split()
    a = []
    for i in range(n):
        a.append(int(string_a[i]))

    s = input()
    dmg = 0;

    i = 0;
    while(i <= len(s) - 1):
        c = s[i]
        j = i + 1
        while(j <= len(s) - 1):
            if(s[j] == s[i]):
                j += 1
                continue;
            else:
                break;
        if(j - i <= k):
            for m in range(i, j):
                dmg += a[m]
        else:
            temp_a = a[i : j]
            temp_a.sort(reverse = True)
            for m in range(k):
                dmg += temp_a[m]
        i = j

    print(dmg)


#!/usr/bin/python

if __name__ == "__main__":
    n , k = map(int, input().split())
    string_a = input().split()
    a = []
    for i in range(n):
        a.append(int(string_a[i]))

    s = input()
    dmg = 0;

    i = 0;
    while(i <= len(s) - 1):
        c = s[i]
        j = i + 1
        while(j <= len(s) - 1):
            if(s[j] == s[i]):
                j += 1
                continue;
            else:
                break;
        if(j - i <= k):
            for m in range(i, j):
                dmg += a[m]
        else:
            temp_a = a[i : j]
            for m in range(k):
                max_temp_a = max(temp_a)
                dmg += max_temp_a
                temp_a.remove(max_temp_a)
        i = j

    print(dmg)


N, K = [int(x) for x in input().split()]
W = [int(x) for x in input().split()]
S = input()
index = 0
intervals = [] # [)
while index < N:
    i = index
    while i < N-1:
        if S[i+1] == S[i]:
            i += 1
        else:
            break
    intervals.append((index, i))
    index = i + 1
result = 0
for x, y in intervals:
    result += sum(sorted(W[x:y+1], reverse=True)[:K])
print(result)


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 16:58:00 2019

@author: avina
"""

n,t = map(int, input().strip().split())

L = list(map(int, input().strip().split()))
S = list(input().strip())
j = [L[0]]
sums = L[0]
g = 1
action = S[0]
for i in range(1,n):
    if action != S[i]:
        sums +=L[i]
        g = 1
        action = S[i]
    else:
        g+=1
        if g > t:
            g = 0
            j = [L[i]]
            s = sums - L[i -t] + L[i]

                #s = sums + L[i]
           # print(i, i - t+1)
           # print(L[i - t+1])
            #print(s,sums)
            sums = max(s,sums)
        else:
            f = min(j)
            if f > L[i]:
                j = [L[i+1]]
                g = 0
            else:
                sums +=L[i]
                j.append(L[i])

    #print(sums)
print(sums)


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 22:45:09 2019

@author: avina
"""

n,t = map(int, input().strip().split())

L = list(map(int, input().strip().split()))
k = list(input().strip())
a = k[0]
sums = 0
j = 0
for i in range(1,n):
    if a != k[i]:
        G = L[j:i]
        G.sort(reverse=True)
        if len(G) <= t:
            sums += sum(G)
        else:
            sums += sum(G[:t])
        j = i
        a = k[i]

G = L[j:]
G.sort(reverse=True)
if len(G)<=t:
    sums+=sum(G)
else:
    sums += sum(G[:t])
print(sums)


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 16:58:00 2019

@author: avina
"""

n,t = map(int, input().strip().split())

L = list(map(int, input().strip().split()))
S = list(input().strip())
j = [L[0]]
sums = L[0]
g = 1
action = S[0]
for i in range(1,n):
    if action != S[i]:
        sums +=L[i]
        g = 1
        action = S[i]
    else:
        g+=1
        if g > t:
            g = 0
            j = [L[i]]
            s = sums - L[i -t] + L[i]

                #s = sums + L[i]
            print(i, i - t+1)
            print(L[i - t+1])
            #print(s,sums)
            sums = max(s,sums)
        else:
            f = min(j)
            if f > L[i]:
                j = [L[i+1]]
                g = 0
            else:
                sums +=L[i]
                j.append(L[i])

    #print(sums)
print(sums)


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 16:58:00 2019

@author: avina
"""

n,t = map(int, input().strip().split())

L = list(map(int, input().strip().split()))
S = list(input().strip())
#j = [L[0]]
sums = L[0]
g = 1
action = S[0]
for i in range(1,n):
    if action != S[i]:
        sums +=L[i]
        g = 1
        action = S[i]
    else:
        g+=1
        if g > t:
            g = 0
            #j = [L[i]]
            s = sums - L[i -t] + L[i]

                #s = sums + L[i]
           # print(i, i - t+1)
           # print(L[i - t+1])
            #print(s,sums)
            sums = max(s,sums)
        else:
            #f = min(j)
            #if f > L[i]:
            #    j = [L[i+1]]
            #    g = 0
            #else:
            sums +=L[i]
               # j.append(L[i])

    #print(sums)
print(sums)


n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
s = input() + "-"
d = [0] * 26
ll = "0"
dmg = 0
cur = []
ll = s[0]
for i in range(len(s)):
    if ll != s[i]:
        cur.sort(key=lambda x:-x)
        dmg += sum(cur[:k])
        if i < n:
            cur = [a[i]]
    else:
        cur.append(a[i])
    ll = s[i]
print(dmg)


n, k = map(int, input().split())
l = list(map(int, input().split()))
s = input()
if n == 1 and k == 1:
    print(l[0])
    exit()
def f(beg, i):
    x = l[beg: i]
    if i - beg <= k:
        return sum(i for i in x)
    else:
        x = sorted(x)
        return sum(x) - sum(x[0: i - beg - k])

i = 1
beg = 0
prev = s[0]
sm = 0
while i < n:
    if s[i] == s[i - 1]:
        prev = prev + s[i]
    else:
        sm += f(beg, i)
        beg = i
        prev = s[i]
    if i == (n - 1):
        sm += f(beg, i + 1)
    i += 1
print(sm)


n, k = map(int, input().split())
l = list(map(int, input().split()))
s = input()

def f(beg, i):
    x = l[beg: i]
    if i - beg <= k:
        return sum(i for i in x)
    else:
        x = sorted(x)
        return sum(x) - sum(x[0: i - beg - k])

i = 1
beg = 0
prev = s[0]
sm = 0
while i < n:
    if s[i] == s[i - 1]:
        prev = prev + s[i]
    else:
        sm += f(beg, i)
        beg = i
        prev = s[i]
    if i == (n - 1):
        sm += f(beg, i + 1)
    i += 1
print(sm)


import heapq

def rlist(): return list(map(int, input().split()))
def rdi(): return int(input())

n, k = rlist()
hp = rlist()
line = input()
last = ''
cnt = 0
dmg = 0
ll = list()
for i in range(n):
    elem = line[i]
    if elem != last:
        ll.append([])
        last = elem
    heapq.heappush(ll[-1], -hp[i])
for heap in ll:
    for i in range(min(len(heap), k)):
        e = -heapq.heappop(heap)
        dmg += e
print(dmg)


import itertools

n, k = list(map(int,input().split()))
an = list(map(int,input().split()))
s = input()

# print(n,k)
# print(an)
# print(s)
res = 0
now = 0
for c, g in itertools.groupby(s):
    l = len(list(g))
    if l <= k:
        res += sum(an[now:now+l])
    if l > k:
        res += sum(sorted(an[now:now+l])[-k:])
    # print(c,res)
    now += l
print(res)


import itertools
n, k = list(map(int,input().split()))
an = list(map(int,input().split()))
s = input()
res = now= 0
for c, g in itertools.groupby(s):
    l = len(list(g))
    if l <= k:
        res += sum(an[now:now+l])
    else:
        res += sum(sorted(an[now:now+l])[-k:])
    now += l
print(res)


n,k = list(map(int, input().split()))
a = list(map(int, input().split()))
s = input()

st = []
dmg = 0
st.append(a[0])
for i in range(1,n):
	if s[i] == s[i-1]:
		st.append(a[i])
	else:
		#print(sorted(list(st)))
		dmg += sum(sorted(list(st))[-k:])
		st = []
		st.append(a[i])
		#print('Increased to:', dmg)
#print('final:', st, sum(list(st)[-k:]))
dmg += sum(sorted(list(st))[-k:])
print(dmg)


n,k = list(map(int, input().split()))
a = list(map(int, input().split()))
s = input()

st = []
dmg = 0
st.append(a[0])
for i in range(1,n):
	if s[i] == s[i-1]:
		st.append(a[i])
	else:
		#print(sorted(list(st)))
		dmg += sum(sorted(list(st))[-k:])
		st = set()
		st.append(a[i])
		#print('Increased to:', dmg)
#print('final:', st, sum(list(st)[-k:]))
dmg += sum(sorted(list(st))[-k:])
print(dmg)


n,k = list(map(int, input().split()))
a = list(map(int, input().split()))
s = input()

st = set()
dmg = 0
st.add(a[0])
for i in range(1,n):
	if s[i] == s[i-1]:
		st.add(a[i])
	else:
		#print(sorted(list(st)))
		dmg += sum(sorted(list(st))[-k:])
		st = set()
		st.add(a[i])
		#print('Increased to:', dmg)
#print('final:', st, sum(list(st)[-k:]))
dmg += sum(sorted(list(st))[-k:])
print(dmg)


a,b=map(int,input().split())
c=list(map(int,input().split()))
d=input()
pred=d[0]
cnt=1
su=0
l=0
r=0
d+='9'
for i in range(1,a+1):
    if d[i]==pred:
        cnt+=1
        r+=1
    else:
        if cnt<=b:
            su+=sum (c[l:r+1])
        else:
            s=c[l:r+1]
            s.sort()
            for j in range(b):
                su+=s[cnt-j-1]
        cnt=1
        l=r+1
        r+=1
    pred=d[i]
print(su)


a,b=map(int,input().split())
c=list(map(int,input().split()))
d=input()
pred=d[0]
cnt=1
su=0
l=0
r=0
d+='9'
for i in range(1,a+1):
    if d[i]==pred:
        cnt+=1
        r+=1
    else:
        if cnt<=b:
            su+=sum (c[l:r+1])
        else:
            s=c[l:r+1]
            for j in range(b):
                ma=max(s)
                su+=ma
                s.remove(ma)
        cnt=1
        l=r+1
        r+=1
    pred=d[i]
print(su)


n, m = map(int,input().split())
nums = list(map(int,input().split()))
string = list(input())

dmg = 0
start = 0
end = 0

while end < n:
    while end < n and string[start] == string[end]:
        end+=1
    if (end - start) <= m:
        dmg+= sum(nums[start:end])
    else:
        dmg += sum(sorted(nums[start:end],reverse= True)[:m])
    start = end

print(dmg)


i = 0
n, k = map(int,input().split())

damages = list(map(int,input().split()))
hits = input()
dmg = 0

while i < n:
    j = i + 1
    while j < n and hits[i] == hits[j]:
        j+=1
    dmg += sum(sorted(damages[i:j],reverse= True)[:k])
    i = j
print(dmg)


n, k = map(int, input().split())
p = list(map(int, input().split()))
s = input() + "."
cc = s[0]
ii = 0
r = 0
for i, c in enumerate(s):
    if c != cc:
        r += sum(sorted(p[ii:i], reverse=True)[:k])
        ii = i
        cc = c
print(r)


n,k = map(int,input().split())
lst = list(map(int,input().split()))
s = input()
result,shet,res,mas=0,1,0,[lst[0]]
for i in range(1,n):
    if s[i]==s[i-1]:
        shet+=1
        mas.append(lst[i])
    else:
        if shet>k:
            mas.sort()
            mas.reverse()
            for j in range(k):
                res+=mas[j]
        else:
            res=sum(mas)
        result+=res
        shet,res,mas=1,0,[lst[i]]
if shet>k:
    mas.sort()
    mas.reverse()
    for j in range(k):
        res+=mas[j]
else:
    res=sum(mas)
result+=res
print(result)


import sys
import math

def read_int():
	return int(input().strip())

def read_int_list():
	return list(map(int,input().strip().split()))

def read_string():
	return input().strip()

def read_string_list(delim=" "):
	return input().strip().split(delim)

###### Author : Samir Vyas #######
###### Write Code Below    #######
n,k = read_int_list()
damages = read_int_list()
keys = read_string()

start = 0
damage = 0

while start < n:
	end = start+1
	while end < n and keys[start] == keys[end]:
		end += 1
	sub_list = damages[start:end]
	sub_list.sort(reverse=True)
	damage += sum(sub_list[:k])

	start = end

print(damage)


import numpy as np

fl = list(map(int, input().split(" ")))
sl = np.array(list(map(int, input().split(" "))))
s = input()

i = 0
t = 0
while i < len(s):
    c = 1
    j = i + 1
    while j < len(s):
        if s[j] == s[i]:
            c += 1
        else:
            break
        j += 1
    if c > fl[1]:
        sl[i:j].sort()
        t += sum(sl[j - fl[1] : j])
    else:
        t += sum(sl[i:j])
    i = j
print(t)


fl = list(map(int, input().split(" ")))
sl = list(map(int, input().split(" ")))
s = input()

i = 0
t = 0
while i < len(s):
    c = 1
    j = i + 1
    while j < len(s):
        if s[j] == s[i]:
            c += 1
        else:
            break
        j += 1
    if c > fl[1]:
        sub = sorted(sl[i:j])
        t += sum(sub[c - fl[1] : c])
    else:
        t += sum(sl[i:j])
    i = j
print(t)


n, k = map(int , input().split())
a = list(map(int, input().split()))
str = input()
ans = i = 0
while i<n:
    j = i
    while i < n-1 and str[i+1] == str[i]: i += 1
    ans += sum(sorted(a[j: i+1])[-k:])
    i += 1
print(ans)


'''import random
import math

stdin=open('input.txt')

def input():
	return stdin.readline()[:-1]

stdout=open('output.txt',mode='w+')

def print(x,end='\n'):
	stdout.write(str(x)+end)
'''

# CODE BEGINS HERE.................

n,k=map(int,input().split())
damage = list(map(int,input().split()))
string = input()
count=0
prev=''
skip = [False]*n
for i in range(n):
	if(string[i] == prev):
		count+=1
	else:
		count = 1
	#print(count)

	if(count == k+1):
		min_ = damage[i-k]
		min_index = i-k
		for j in range(i-k+1,i+1):
			if(damage[j]<min_):
				min_ = damage[j]
				min_index = j
		skip[min_index] = True
		count = i-min_index
	prev = string[i]
ans=0
#print(skip)
for i in range(n):
	if skip[i]:
		continue
	ans+=damage[i]
print(ans)

#CODE ENDS HERE....................

#stdout.close()


'''import random
import math

stdin=open('input.txt')

def input():
	return stdin.readline()[:-1]

stdout=open('output.txt',mode='w+')

def print(x,end='\n'):
	stdout.write(str(x)+end)
'''

# CODE BEGINS HERE.................

n,k=map(int,input().split())
damage = list(map(int,input().split()))
string = input()
count=0
prev=''
ans=0
for i in range(n):
	if(string[i] == prev):
		count+=1
	else:
		l= sorted(damage[i-count:i],reverse=True)
		ans+=sum(l[:k])
		count = 1
	prev = string[i]
	#print(count)

l= sorted(damage[i-count+1:i+1],reverse=True)

ans+=sum(l[:k])

print(ans)

#CODE ENDS HERE....................

#stdout.close()


def cal(array,k):
	temp2=0
	ans=0
	while temp2<k:
		ans+=array[temp2]
		temp2+=1
	return ans

n,k=map(int,input().split())
l=list(map(int,input().split()))
s=input()
i=0
j=0
ans=0
while j<n:
	if s[i]==s[j]:
		j+=1
	else:
		if j-i+1<k:
			ans+=sum(l[i:j])
			i=j
		else:
			temp=l[i:j]
			temp.sort(reverse=True)
			ans+=cal(temp,k)
			i=j
if j-i+1<k:
	ans+=sum(l[i:j])
else:
	temp=l[i:j]
	temp.sort(reverse=True)
	ans+=cal(temp,k)
print (ans)


def cal(array,k):
	temp2=0
	ans=0
	while temp2<k:
		ans+=array[temp2]
		temp2+=1
	return ans

n,k=map(int,input().split())
l=list(map(int,input().split()))
s=input()
i=0
j=0
ans=0
while j<n:
	if s[i]==s[j]:
		j+=1
	else:
		if j-i+1<=k:
			ans+=sum(l[i:j])
			i=j
		else:
			temp=l[i:j]
			temp.sort(reverse=True)
			ans+=cal(temp,k)
			i=j
if j-i+1<k:
	ans+=sum(l[i:j])
else:
	temp=l[i:j]
	temp.sort(reverse=True)
	ans+=cal(temp,k)
print (ans)


n,k=map(int,input().split())
l=list(map(int,input().split()))
s=input()
new=""
count=1
for i in range(n-1):
	if s[i]==s[i+1]:
		count+=1
	else:
		new=new+s[i]+str(count)
		count=1
new+=s[-1]+str(count)
#print (new)
i=1
j=0
ans=0
while i<len(new):
	if int(new[i])>k:
		temp=l[j:j+int(new[i])]
		temp.sort(reverse=True)
		temp2=0
		while temp2<k:
			ans+=temp[temp2]
			temp2+=1
		j=j+int(new[i])
	else:
		temp2=0
		while temp2<int(new[i]):
			ans+=l[j]
			j+=1
			temp2+=1
	i+=2
	#print (ans)
print (ans)


n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()
num = 0
tmp = [a[0]]
pre = s[0]
for i in range(1, n):
    if pre != s[i]:
        tmp = sorted(tmp, reverse=True)
        num += sum(tmp[:k])
        tmp = [a[i]]
    else:
        tmp.append(a[i])
    pre = s[i]
tmp = sorted(tmp, reverse=True)
num += sum(tmp[:k])
print(num)


import sys
import itertools
import re
import heapq

data = sys.stdin.read().splitlines()

n, m = map(int, data[0].split())

nums = tuple(map(int, data[1].split()))

s = data[2]
ans = 0
i = 0
for ch, g in itertools.groupby(s):
    l = len(list(g))
    j = i + l
    ans += sum(heapq.nlargest(min(l, m), nums[i:j]))
    i = j
print(ans)


import bisect
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()

cur = 'aa'
res = 0
temp_arr = []
cur_counter = 0
temp_sum = 0
for index, value in enumerate(a):
    if s[index] != cur:
        cur = s[index]
        res += temp_sum
        cur_counter = 1
        temp_arr = [value]
        temp_sum = value
    else:
        cur_counter += 1
        if cur_counter > k and value > temp_arr[0]:
            bisect.insort(temp_arr, value)
            temp_sum+=value
            temp_sum -= temp_arr[0]
            del temp_arr[0]
        elif cur_counter <= k:
            bisect.insort(temp_arr, value)
            temp_sum+=value

res += temp_sum
print(res)


import bisect
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()

cur = 'aa'
res = 0
temp_arr = []
cur_counter = 0
for index, value in enumerate(a):
    if s[index] != cur:
        cur = s[index]
        res += sum(temp_arr)
        cur_counter = 1
        temp_arr = [value]
    else:
        cur_counter += 1
        bisect.insort(temp_arr, value)
        if cur_counter > k:
            del temp_arr[0]
res += sum(temp_arr)
print(res)


import heapq
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()

cur = 'aa'
res = 0
temp_arr = []
cur_counter = 0
temp_sum = 0
for index, value in enumerate(a):
    if s[index] != cur:
        cur = s[index]
        res += temp_sum
        cur_counter = 1
        temp_arr = []
        heapq.heappush(temp_arr, value)
        temp_sum = value
    else:
        cur_counter += 1
        if cur_counter > k and value > temp_arr[0]:
            temp_sum+=value
            smallest = heapq.heappushpop(temp_arr, value)
            temp_sum -= smallest
        elif cur_counter <= k:
            heapq.heappush(temp_arr, value)
            temp_sum+=value

res += temp_sum
print(res)


import bisect
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()

cur = 'aa'
res = 0
temp_arr = []
cur_counter = 0
temp_sum = 0
for index, value in enumerate(a):
    if s[index] != cur:
        cur = s[index]
        res += temp_sum
        cur_counter = 1
        temp_arr = [value]
        temp_sum = value
    else:
        cur_counter += 1
        bisect.insort(temp_arr, value)
        temp_sum+=value
        if cur_counter > k:
            temp_sum -= temp_arr[0]
            del temp_arr[0]
res += temp_sum
print(res)


a,b=map(int,input().split());c=list(map(int,input().split()));d=input();i,s=0,0
while i<a:
    k=d[i];f=[]
    while i<a and d[i]==k:f+=[c[i]];i+=1
    s+=sum(sorted(f)[-b:])
print(s)


a,b=map(int,input().split());c=list(map(int,input().split()));d=input();i,s=0,0
while i<a:
    k=d[i];f=[]
    while i<a and d[i]==k:f+=[c[i]];i+=1
    s+=sum(sorted(f)[::-1][:b])
print(s)


n, k = map(int, input().split())

a = list(map(int, input().split()))

s = input()

answer = i = 0
p = 1

while (p < n):
    if (s[i] == s[p]):
        p += 1

    else:
        part = a[i:p]
        part.sort()
        answer += sum(part[-k:])

        i = p
        p += 1

part = a[i:p]
part.sort()
answer += sum(part[-k:])

print(answer)


import sys
sin = sys.stdin

nk = sin.readline().split()
nk = [int(x) for x in nk]
n = nk[0]
k = nk[1]
damages = sin.readline().split()
damages = [int(x) for x in damages]
hits = list(sin.readline())[:-1]
totalScore = 0
score = 0
prevLetter = ''
istart = 0
icurr = 0

def findBest(lst, k):
    s = sorted(lst)
    return sum(s[len(s)-k:])

while icurr < len(damages):
    if hits[icurr] == prevLetter:
        score += damages[icurr]
    else:
        if icurr - istart > k:
            totalScore += findBest(damages[istart:icurr], k)
            istart = icurr
            score = damages[icurr]
        else:
            totalScore += score
            istart = icurr
            score = damages[icurr]
    prevLetter = hits[icurr]
    icurr += 1
if icurr - istart > k:
    totalScore += findBest(damages[istart:], k)
else:
    totalScore += score

print(totalScore)


n, m = map(int, input().split())
ar = list(map(int, input().split()))
s = input()
d = dict()
for x in range(ord('a'), ord('z') + 1):
    d[chr(x)] = []

for x in range(n):
    d[s[x]].append((x, ar[x]))

for x in d:
    d[x].sort(key=lambda q: q[1], reverse=True)
    d[x] = d[x][:m+1]
    d[x].sort(key = lambda q: q[0], reverse=True)

res = 0
for x in range(n):
    if x == d[s[x]][-1][0]:
        res += ar[x]
        d[s[x]].pop()

print(res)


n, m = map(int, input().split())
ar = list(map(int, input().split()))
s = input()

kek = [0]
last = 'A'
res = 0
for x in range(n):
    if s[x] == last:
        kek.append(ar[x])
    if s[x] != last:
        if len(kek) > m:
            kek.sort(reverse=True)
            kek = kek[:m]
        res += sum(kek)
        kek = [ar[x]]
        last = s[x]
    if x == n-1:
        if len(kek) > m:
            kek.sort(reverse=True)
            kek = kek[:m]
        res += sum(kek)
        kek = [ar[x]]
        last = s[x]

print(res)


n, k = [int(s) for s in input().split(' ')]
damages = [int(s) for s in input().split(' ')]
string = input()
totalDamage = 0
prevButton = None
prevDamages = []
for i in range(n):
    if string[i] == prevButton:
        prevDamages.append(damages[i])
    else:
        totalDamage += sum(sorted(prevDamages, reverse=True)[:k])
        prevDamages = [damages[i]]
        prevButton = string[i]
totalDamage += sum(sorted(prevDamages, reverse=True)[:k])
print(totalDamage)


from sys import stdin
read = stdin.readline

n,k = map(int,read().split())
A = list(map(int,read().split()))
s = read()

pc = pi = 0
tot = 0
for i,c in enumerate(s):
    if c != pc:
        if i - pi > k:
            tot += sum(sorted(A[pi:i])[-k:])
        else:
            tot += sum(A[pi:i])

        pi,pc = i,c

print(tot)


n,b=input().split()
n=int(n)
b=int(b)
j=0
lt=[]
tempLt=[]
lt=list(map(int,input().split()))
str=input()
for i in range(len(str)):
    if i==0:
        tempLt.append(lt[i])
        j=0
    elif str[i]==str[i-1]:
        tempLt.append(lt[i])
    else:
        tempLt.sort()
        tempLt.reverse()
        for k in range(j,i):
            lt[k]=tempLt[k-j]
        del tempLt
        tempLt=[]
        5
        tempLt.append(lt[i])
        j=i
tempLt.sort()
tempLt.reverse()
for k in range(j,i+1):
    lt[k]=tempLt[k-j]
dmg=lt[0]
counter=1
for i in range(1,len(str)):
    if str[i]==str[i-1]:
        if counter<b:
            counter+=1
            dmg+=lt[i]
    else:
        counter=1
        dmg+=lt[i]
print(dmg)


n,k=map(int,input().split())
l=list(map(int,input().split()))
s=input()
sum=l[0]
arr=[l[0]]
count=1
for i in range(1,n):
  if s[i]==s[i-1]:
    count=count+1
    if count<=k:
      sum=sum+l[i]
      arr.append(l[i])
    else:
      arr.sort()
      if arr[0]<l[i]:
        z=arr.pop(0)
        sum=sum-z+l[i]
        arr.append(l[i])
      count=count-1
  else:
    arr=[l[i]]
    count=1
    sum=sum+l[i]
print(sum)


import bisect
from sys import stdin,stdout
n,k=map(int,stdin.readline().split())
l=list(map(int,stdin.readline().split()))
s=input()
suma=0
arr=[l[0]]
for i in range(1,n):
  if s[i-1]==s[i]:
    arr.append(l[i])
  else:
    arr.sort(reverse = True)
    suma += sum(arr[:k])
    arr = [l[i]]
arr.sort(reverse = True)
suma += sum(arr[:k])
print(suma)


n, k = gets.strip.split(' ').map(&:to_i)
a = gets.strip.split(' ').map(&:to_i)
h = gets.strip.split('').to_a

res = 0
last = h[0]
tmp = []
idx = 0

while idx < a.size
  if idx.zero?
    tmp << a[idx]
    idx += 1
    next
  end
  if h[idx] != h[idx - 1]
    res += tmp.size.zero? ? 0 : tmp.sort.reverse.slice(0, k).inject(:+)
    tmp = [a[idx]]
  else
    tmp << a[idx]
  end
  idx += 1
end
if tmp.size > 0
  res += tmp.size.zero? ? 0 : tmp.sort.reverse.slice(0, k).inject(:+)
end
puts res


if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

#use moving window to get the sum
nk = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]
a = gets.chomp.split(" ").map(&:to_i)
s = gets.chomp

arr = [0]
breakpoints = 2
(1..n-1).each do |i|
	if s[i]!=s[i-1]
		breakpoints+=1
		arr.push i
	end
end
arr.push n

bigarr = []
(0..breakpoints-2).each do |st|
	newarr = []
	newlen = 1
	min = 1.0/0.0
	sum = 0
	(arr[st]..arr[st+1]-1).each do |range|
		this = a[range]
#		p newlen
		if(newlen<=k)
			newarr.push this
			sum+=this
#			min = this if this<min
			newlen+=1
		else
			if (this>newarr[0])
				asd = newarr.shift
				sum-=asd
				sum+=this
				newarr.push this
#				newarr.delete_at(newarr.index(min))
#				min = newarr.min
			end
		end
		newarr.sort!
#		p newarr
		bigarr.push sum
	end
end

totsum = 0
(0..breakpoints-2).each do |st|
	totsum += bigarr[arr[st]..arr[st+1]-1].max
end

#p arr
#p bigarr
puts totsum


if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

#use moving window to get the sum
nk = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]
a = gets.chomp.split(" ").map(&:to_i)
s = gets.chomp

arr = [0]
breakpoints = 2
(1..n-1).each do |i|
	if s[i]!=s[i-1]
		breakpoints+=1
		arr.push i
	end
end
arr.push n

bigarr = []
(0..breakpoints-2).each do |st|
	newarr = []
	newlen = 1
	min = 1.0/0.0
	sum = 0
	(arr[st]..arr[st+1]-1).each do |range|
		this = a[range]
#		p newlen
		if(newlen<=k)
			newarr.push this
			sum+=this
#			min = this if this<min
			newlen+=1
		else
			if (this>min)
				sum-=newarr.pop
				sum+=this
				newarr.push this
#				newarr.delete_at(newarr.index(min))
#				min = newarr.min
			end
		end
		newarr.sort!
		bigarr.push sum
	end
end

totsum = 0
(0..breakpoints-2).each do |st|
	totsum += bigarr[arr[st]..arr[st+1]-1].max
end

#p arr
#p bigarr
puts totsum


if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

#use moving window to get the sum
nk = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]
a = gets.chomp.split(" ").map(&:to_i)
s = gets.chomp

arr = [0]
breakpoints = 2
(1..n-1).each do |i|
	if s[i]!=s[i-1]
		breakpoints+=1
		arr.push i
	end
end
arr.push n

#bigarr = []
totsum = 0
(0..breakpoints-2).each do |st|
	newarr = []
	newlen = 1
	min = 1.0/0.0
	sum = 0
	max = 0
	(arr[st]..arr[st+1]-1).each do |range|
		this = a[range]
#		p newlen
		if(newlen<=k)
			newarr.push this
			sum+=this
			min = this if this<min
			newlen+=1
		else
			if (this>min)
				sum-=min
				sum+=this
				newarr.push this
				newarr.delete_at(newarr.index(min))
				min = newarr.min
			end
		end
		max = sum if sum>max
	end
	totsum += sum
end

#p arr
puts totsum


if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

#use moving window to get the sum
nk = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]
a = gets.chomp.split(" ").map(&:to_i)
s = gets.chomp

arr = [0]
breakpoints = 2
(1..n-1).each do |i|
	if s[i]!=s[i-1]
		breakpoints+=1
		arr.push i
	end
end
arr.push n

totsum = 0
#bigarr = []
=begin

(0..breakpoints-2).each do |st|
	newarr = []
	newlen = 1
	min = 1.0/0.0
	sum = 0
	max = 0
	(arr[st]..arr[st+1]-1).each do |range|
		this = a[range]
#		p newlen
		if(newlen<=k)
			newarr.push this
			sum+=this
			min = this if this<min
			newlen+=1
		else
			if (this>min)
				sum-=min
				sum+=this
				newarr.push this
				newarr.delete_at(newarr.index(min))
				min = newarr.min
			end
		end
		max = sum if sum>max
	end
	totsum += sum
end
=end
#p arr
(0..breakpoints-2).each do |st|
	newarr = a[arr[st]..arr[st+1]-1].sort
#	p newarr
	initi = newarr.length-1
	i = initi
	min = arr[st]
	sum = 0
#	p initi
	while true
		break if (initi-i+1)>k
		break if i<0
#		p i
		sum+=newarr[i]
		i -= 1
#		p sum
	end
#	p sum
	totsum += sum
end

#p arr
puts totsum


if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

#use moving window to get the sum
nk = gets.chomp.split(" ").map(&:to_i)
n = nk[0]
k = nk[1]
a = gets.chomp.split(" ").map(&:to_i)
s = gets.chomp

arr = [0]
breakpoints = 2
(1..n-1).each do |i|
	if s[i]!=s[i-1]
		breakpoints+=1
		arr.push i
	end
end
arr.push n

bigarr = []
(0..breakpoints-2).each do |st|
	newarr = []
	newlen = 1
	min = 1.0/0.0
	sum = 0
	(arr[st]..arr[st+1]-1).each do |range|
		this = a[range]
#		p newlen
		if(newlen<=k)
			newarr.push this
			sum+=this
			min = this if this<min
			newlen+=1
		else
			if (this>min)
				sum-=min
				sum+=this
				newarr.push this
				newarr.delete_at(newarr.index(min))
				min = newarr.min
			end
		end
		bigarr.push sum
	end
end

totsum = 0
(0..breakpoints-2).each do |st|
	totsum += bigarr[arr[st]..arr[st+1]-1].max
end

#p arr
#p bigarr
puts totsum


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
s = raw_input()
l=[0]
for x in range(n-1):
	if s[x]!=s[x+1]:
		l.append(x+1)
l.append(n)
ans=0
# print l
for x in xrange(len(l)-1):
	temp=a[l[x]:l[x+1]]
	# print temp
	ls=l[x+1]-l[x]
	temp.sort()
	ans+=sum(temp[ls-k:ls])
print ans


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
s = raw_input()
l=[0]
for x in range(n-1):
	if s[x]!=s[x+1]:
		l.append(x+1)
l.append(n)
ans=0
# print l
for x in xrange(len(l)-1):
	temp=a[l[x]:l[x+1]]
	# print temp
	ls=l[x+1]-l[x]
	temp.sort()
	if ls-k>=0:
		ans+=sum(temp[ls-k:ls])
	else:
		ans+=sum(temp[ls-k:ls])
print ans


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
s = '0'+raw_input()+'0'
l=[]
for x in range(n+1):
	if s[x]!=s[x+1]:
		l.append(x)
ans=0
# print l
for x in xrange(len(l)-1):
	temp=a[l[x]:l[x+1]]
	# print temp
	ls=l[x+1]-l[x]
	temp.sort()
	ans+=sum(temp[ls-k:ls])
print ans


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
s = '0'+raw_input()+'1'
l=[]
for x in range(n+1):
	if s[x]!=s[x+1]:
		l.append(x)
ans=0
# print l
for x in xrange(len(l)-1):
	temp=a[l[x]:l[x+1]]
	# print temp
	ls=l[x+1]-l[x]
	temp.sort()
	ans+=sum(temp[ls-k:ls])
print ans


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
s = raw_input()
l=[0]
for x in range(n-1):
	if s[x]!=s[x+1]:
		l.append(x+1)
l.append(n)
ans=0
# print l
for x in xrange(len(l)-1):
	temp=a[l[x]:l[x+1]]
	# print temp
	ls=l[x+1]-l[x]
	temp.sort()
	if ls-k>=0:
		ans+=sum(temp[ls-k:ls])
	else:
		ans+=sum(temp)
print ans


n,k = map(int,raw_input().split())
a = map(int,raw_input().split())
s = raw_input()
l=[0]
for x in range(n-1):
	if s[x]!=s[x+1]:
		l.append(x+1)
l.append(n)
ans=0
print l
for x in xrange(len(l)-1):
	temp=a[l[x]:l[x+1]]
	# print temp
	ls=l[x+1]-l[x]
	temp.sort()
	ans+=sum(temp[ls-k:ls])
print ans


n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
s=list(raw_input())
x=0
while s:
    c=s[-1]
    v=[]
    while s and c==s[-1]:
        s.pop()
        v+=a.pop(),
    if len(v)>m:
        x+=sum(sorted(v)[-m:])
    else:
        x+=sum(v)
print x


import sys
import operator

def get_sub_seq_hit(seq_hits, k):
    start = 0
    end =  start + 1
    sub_seq = []
    while end < len(seq_hits):
        if seq_hits[start] == seq_hits[end]:
            end += 1
        else:
            if end - start > k:
                sub_seq.append((start, end))
            start = end
            end = start + 1

    if end - start > k:
        sub_seq.append((start, end))
    return sub_seq

n, k = map(int, sys.stdin.readline().strip().split(" "))

lst_dmg = map(int, sys.stdin.readline().strip().split(" "))

lst_seq_hits = sys.stdin.readline().strip()
total_dmg = sum(lst_dmg)

freq_button = {}
# print lst_seq_hits
# print lst_dmg

lst_sub_seq_hits = get_sub_seq_hit(lst_seq_hits, k)

for sub_seq in lst_sub_seq_hits:
    start, end = sub_seq
    # print start, end
    sorted_dmg = sorted(zip(range(start, end), lst_dmg[start:end]), key=operator.itemgetter(1))
    # print sorted_dmg
    for i in range(end - start - k):
        # print i, sorted_dmg[i]
        lst_dmg[sorted_dmg[i][0]] = 0

# print lst_dmg
final_dmg = sum(lst_dmg)
sys.stdout.write("%d\n" % final_dmg)


import sys
import operator

def get_sub_seq_hit(seq_hits, k):
    start = 0
    end =  start + 1
    sub_seq = []
    while end < len(seq_hits):
        if seq_hits[start] == seq_hits[end]:
            end += 1
        else:
            if end - start > k:
                sub_seq.append((start, end))
            start += end
            end = start + 1

    return sub_seq

n, k = map(int, sys.stdin.readline().strip().split(" "))

lst_dmg = map(int, sys.stdin.readline().strip().split(" "))

lst_seq_hits = sys.stdin.readline().strip()
total_dmg = sum(lst_dmg)

freq_button = {}

# print lst_dmg

lst_sub_seq_hits = get_sub_seq_hit(lst_seq_hits, k)

for sub_seq in lst_sub_seq_hits:
    start, end = sub_seq
    # print start, end
    sorted_dmg = sorted(zip(range(start, end), lst_dmg[start:end]), key=operator.itemgetter(1))
    # print sorted_dmg
    for i in range(end - start - k):
        # print i, sorted_dmg[i]
        lst_dmg[sorted_dmg[i][0]] = 0

# print lst_dmg
final_dmg = sum(lst_dmg)
sys.stdout.write("%d\n" % final_dmg)


import sys
import operator

def get_sub_seq_hit(seq_hits, k):
    start = 0
    end =  start + 1
    sub_seq = []
    while end < len(seq_hits):
        if seq_hits[start] == seq_hits[end]:
            end += 1
        else:
            if end - start > k:
                sub_seq.append((start, end))
            start += end
            end = start + 1

    if end - start > k:
        sub_seq.append((start, end))
    return sub_seq

n, k = map(int, sys.stdin.readline().strip().split(" "))

lst_dmg = map(int, sys.stdin.readline().strip().split(" "))

lst_seq_hits = sys.stdin.readline().strip()
total_dmg = sum(lst_dmg)

freq_button = {}

# print lst_dmg

lst_sub_seq_hits = get_sub_seq_hit(lst_seq_hits, k)

for sub_seq in lst_sub_seq_hits:
    start, end = sub_seq
    # print start, end
    sorted_dmg = sorted(zip(range(start, end), lst_dmg[start:end]), key=operator.itemgetter(1))
    # print sorted_dmg
    for i in range(end - start - k):
        # print i, sorted_dmg[i]
        lst_dmg[sorted_dmg[i][0]] = 0

# print lst_dmg
final_dmg = sum(lst_dmg)
sys.stdout.write("%d\n" % final_dmg)


n, k = map(int, raw_input().split())
l = map(int, raw_input().split())
s = raw_input()
costs = [[l[0]]]
for i in range(1, n):
    if s[i] == s[i-1]:
        costs[-1].append(l[i])
    else:
        costs.append([l[i]])
for i in range(len(costs)):
    costs[i].sort(reverse = True)
ans = 0
for i in costs:
    ans += sum(i[0:min(k, len(i))])
print ans


inp=map(int,raw_input().split())
inp2=map(int,raw_input().split())
inp3=raw_input()
counter=1
last=None
L=[]
for i in range(inp[0]):
    if inp3[i]==last:
        counter+=1
    elif i!=0:
        L.append(counter)
        counter=1
    last=inp3[i]
    # print last
L.append(counter)
# print L
sum=0
def choosebest(arr,l):
    sum=0
    # print arr
    if l>len(arr):l=len(arr)
    arr=sorted(arr)
    arr.reverse()
    # print arr
    for i in arr[:l:]:
        sum+=i
    return sum
ctr=0
for i in L:
    sum+=choosebest(inp2[ctr:ctr+i],inp[1])
    # print i,ctr
    ctr+=i
print sum


inp=map(int,raw_input().split())
inp2=map(int,raw_input().split())
inp3=raw_input()
counter=1
last=None
L=[]
for i in range(inp[0]):
    if inp3[i]==last:
        counter+=1
    elif i!=0:
        L.append(counter)
        counter=1
    last=inp3[i]
    # print last
L.append(counter)
# print L
sum=0
def choosebest(arr,l):
    ini=0
    inup=l-1
    sum=0
    if l>len(arr):l=len(arr)
    # print "cb:",arr,l
    for i in range(l):
        sum+=arr[i]
    best=sum
    while inup<len(arr)-1:
        inup+=1
        ini+=1
        sum+=arr[inup]
        sum-=arr[ini-1]
        if sum>best:
            best=sum
    # print "best is:",best
    return best
ctr=0
for i in L:
    sum+=choosebest(inp2[ctr:ctr+i],inp[1])
    # print i,ctr
    ctr+=i
print sum


k, n = [int(x) for x in raw_input().split()]

forces = [int(x) for x in raw_input().split()]
moves = list(raw_input())

start = (0, moves[0])
sumation = 0
partitions = []
for i in range(0,k):
    # print moves[i], i, n, str(start[0] == i - n)
    if start[1] != moves[i]:
        # print "Letters not matching"
        if(start[0] <= i-n):
            # print "Strike = " + str(i - start[0])
            # print "sum = ",sorted(forces[start[0]:i], reverse=True)[0:n]
            sumation += sum(sorted(forces[start[0]:i], reverse=True)[0:n])
            # partitions.append((start[0],i))
        else:
            # print forces[start[0]:i]
            sumation += sum(forces[start[0]:i])
        start = (i, moves[i])

if(start[0] <= i+1-n):
    sumation += sum(sorted(forces[start[0]:i+1], reverse=True)[0:n])
else:
    # print forces[start[0]:i+1]
    sumation += sum(forces[start[0]:i+1])

print sumation


from collections import deque
import heapq

n, k = map(int, raw_input().split())

a = map(int, raw_input().split())
s = raw_input()
d = [a[0]]
p = s[0]
su = 0
for i, j in zip(list(s[1:]) + ["What"], a[1:] + [0]):
    if i == p:
        heapq.heappush(d, j)
    else:
        if len(d) <= k:
            su += sum(d)
        else:
            su += sum(heapq.nlargest(k, d))
        d = [j]
    p = i
print su


n,k = raw_input().split(' ')
n = int(n)
k = int(k)

dmg = [int(i) for i in raw_input().split(' ')]

s = raw_input()

ans = 0
start = s[0]
a = [dmg[0]]
for i,c in enumerate(s[1:]):
    i=i+1
    if c == start:
        a.append(dmg[i])
        start = c
    else:
        a = sorted(a)
        ans += sum(a[-k:])
        a = [dmg[i]]
        start = c

a = sorted(a)
ans += sum((a[-k:]))
print ans


n,k = map(int, raw_input().split())
list = map(int, raw_input().split())
string = raw_input().strip()
for i in range(n):
    list[i] = (list[i],string[i])
i=0
beta=0
arr=[]
dmg=0
var=string[i]
while beta!=n:
    arr=[]
    var=string[beta]
    while i<n and string[i]==var:
        arr.append(list[i])
        i+=1
        beta+=1
    arr.sort()
    arr.reverse()
    if len(arr)>=k:
        for alpha in range(k):
            dmg+=arr[alpha][0]
    else:
        for alpha in range(len(arr)):
            dmg+=arr[alpha][0]
print dmg


from collections import Counter
n,k=map(int,raw_input().split())
l=map(int,raw_input().split())
s=raw_input()
d=Counter()
d[l[0]]=1
ans=0
for i in range(1,n):
    if s[i]!=s[i-1]:
        #print d.keys()
        c=0
        for j in sorted(d.keys(),reverse=True):
            if c>=k:
                break
            #print j
            ans+=(j*(min(k-c,d[j])))
            c+=d[j]
        d=Counter()
        d[l[i]]=1
    else:
        d[l[i]]+=1
c=0
for j in sorted(d.keys(),reverse=True):
    if c>=k:
        break
    ans+=j*(min(k-c,d[j]))
    c+=d[j]

print ans


s = map(int, raw_input().rstrip().split())
n = s[0]
k = s[1]
hits = map(int, raw_input().rstrip().split())
let = str(raw_input())

conta = []

conta.append(0)
for i in range(1,n):
    if let[i-1] != let[i]:
        conta.append(i)

risultato = 0

if len(conta) != 1:
    hits_let = []
    hits_let.append(hits[:conta[1]])
    for i in range(1,len(conta)-1):
        hits_let.append(hits[conta[i] : conta[i+1]])
    hits_let.append(hits[conta[-1]:])
    for i in range(len(hits_let)):
        if len(hits_let[i]) <= k:
            risultato += sum(hits_let[i])
        else:
            j = len(hits_let[i])-k
            o = sorted(hits_let[i])
            risultato += sum(o[j:])
else:
    if n <= k:
        risultato = sum(hits)
    else:
        o = sorted(hits)
        risultato += sum(o[n-k:])

print(risultato)


s = map(int, raw_input().rstrip().split())
n = s[0]
k = s[1]
hits = map(int, raw_input().rstrip().split())
let = str(raw_input())

conta = []

conta.append(0)
for i in range(1,n):
    if let[i-1] != let[i]:
        conta.append(i)

risultato = 0

if len(conta) != 1:
    hits_let = []
    hits_let.append(hits[:conta[1]])
    for i in range(1,len(conta)-1):
        hits_let.append(hits[conta[i] : conta[i+1]])
    hits_let.append(hits[conta[-1]:])
    for i in range(len(hits_let)):
        if len(hits_let[i]) <= k:
            risultato += sum(hits_let[i])
        else:
            for j in range(len(hits_let[i]) - k):
                hits_let[i].remove(min(hits_let[i]))
            risultato += sum(hits_let[i])
else:
    if n <= k:
            risultato += sum(hits)
    else:
        for j in range(n - k):
            hits.remove(min(hits))
        risultato += sum(hits)

print(risultato)


n,k=map(int,raw_input().split())
val=map(long,raw_input().split())
s=raw_input()

temp=s[0]
temp_list=[val[0]]
ans=0

for i in range(1,len(s)):

    if s[i]==temp:
        temp_list.append(val[i])

    else:
        if len(temp_list)>k:
            temp_list.sort()
            for j in range(len(temp_list)-1,len(temp_list)-k-1,-1):
                ans+=temp_list[j]
            #print ans
        else:
            #print "iwje",temp
            ans+=sum(temp_list)
            #print ans

        temp_list=[val[i]]
        temp=s[i]

if len(temp_list)>k:
    temp_list.sort()
    for j in range(len(temp_list)-1,len(temp_list)-k-1,-1):
        ans+=temp_list[j]
else:
    ans+=sum(temp_list)

print ans


def f(n,k,l,s):
    cha = s[0]
    starter = 0
    sol = 0
    for idx in range(1,n):
        if cha != s[idx]:
            lis = sorted(l[starter:idx])[::-1]
            sol += sum(lis[0:k])
            starter = idx
            cha = s[idx]
        else:
            pass
    lis = sorted(l[starter:])[::-1]
    sol += sum(lis[0:k])
    print sol

if __name__ == '__main__':
    [n,k] = map(int, raw_input().rstrip().split())
    l = map(int, raw_input().rstrip().split())
    s = str(raw_input())
    f(n,k,l,s)


def split_by_unique(s):
    res=[]
    cur=[s[0]]
    for x in s[1:]:
        if x==cur[-1]:
            cur.append(x)
        else:
            res.append(len(cur))
            cur = [x]
    res.append(len(cur))
    return res

n,k=map(int, raw_input().split())
l=map(int, raw_input().split())
s=raw_input()
s=split_by_unique(s)
cur_index = 0
res = 0
for nb in s:
    if nb <= k:
        res += sum(l[cur_index:cur_index+nb])
    else:
        res+= sum(sorted(l[cur_index:cur_index+nb])[-k:])
    cur_index += nb
print res


using System;
using System.Collections.Generic;

namespace CodeForces36_A
{
    class Program
    {
        static void Main(string[] args)
        {
            int len = Convert.ToInt16(Console.ReadLine());
            string s = Console.ReadLine();
            List<int> lst = new List<int>();
            for (int i = 0; i < len; i++)
            {
                if (s[i] == '1')
                    lst.Add(i);
            }
            string res = "YES";
            int step = lst[1] - lst[0];
            for (int i = 0; i < lst.Count-1; i++)
            {
                if (lst[i + 1] - lst[i] != step)
                {
                    res = "NO";
                }
            }
            Console.WriteLine(res);
            //
        }
    }
}


using System;
using System.IO;
using System.Collections.Generic;

namespace CodeForces36_A
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader("input.txt");
            int len = Convert.ToInt16(sr.ReadLine());
            string s = sr.ReadLine();
            sr.Close();
            List<int> lst = new List<int>();
            for (int i = 0; i < len; i++)
            {
                if (s[i] == '1')
                    lst.Add(i);
            }
            string res = "YES";
            int step = lst[1] - lst[0];
            for (int i = 0; i < lst.Count-1; i++)
            {
                if (lst[i + 1] - lst[i] != step)
                {
                    res = "NO";
                }
            }
            StreamWriter sw = new StreamWriter("output.txt");
            sw.WriteLine(res);
            sw.Close();
            //
            //
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace CodeForces36_A
{
    class Program
    {
        static void Main(string[] args)
        {
            int len = Convert.ToInt16(Console.ReadLine());
            string s = Console.ReadLine();
            List<int> lst = new List<int>();
            for (int i = 0; i < len; i++)
            {
                if (s[i] == '1')
                    lst.Add(i);
            }
            string res = "YES";
            int step = lst[1] - lst[0];
            for (int i = 0; i < lst.Count-1; i++)
            {
                if (lst[i + 1] - lst[i] != step)
                {
                    res = "NO";
                }
            }
            Console.WriteLine(res);
            //Console.ReadLine();
        }
    }
}


using System;
using System.Collections.Generic;

namespace CodeForces36_A
{
    class Program
    {
        static void Main(string[] args)
        {
            int len = Convert.ToInt16(Console.ReadLine());
            string s = Console.ReadLine();
            List<int> lst = new List<int>();
            for (int i = 0; i < len; i++)
            {
                if (s[i] == '1')
                    lst.Add(i);
            }
            string res = "YES";
            int step = lst[1] - lst[0];
            for (int i = 0; i < lst.Count-1; i++)
            {
                if (lst[i + 1] - lst[i] != step)
                {
                    res = "NO";
                }
            }
            Console.WriteLine(res);
            //
            //
        }
    }
}


using System;
using System.IO;
using System.Text;

namespace Task_36A
{
    class Program
    {
        static void Main(string[] args)
        {
            //int N = int.Parse(Console.ReadLine());
            //string s = Console.ReadLine(), ans = "YES";
            string s, ans = "YES";
            int N;
            var fileStream = new FileStream(@"input.txt", FileMode.Open, FileAccess.Read);
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
            {
                N = int.Parse(streamReader.ReadLine());
                s = streamReader.ReadLine();
            }

            //    int prevDiff = -1, onePrevIndex = -1;
            //for(int i = 0; i < N; i++)
            //{
            //    if (s[i] == '1' && onePrevIndex == -1)
            //        onePrevIndex = i;
            //    else if(s[i]=='1' && prevDiff == -1)
            //    {
            //        prevDiff = i - onePrevIndex;
            //        onePrevIndex = i;
            //    }
            //    else if (s[i] == '1')
            //    {
            //        int currentDiff = i - onePrevIndex;
            //        if(currentDiff != prevDiff)
            //        {
            //            ans = "NO";
            //            break;
            //        }
            //        onePrevIndex = i;
            //    }
            //}
            ////Console.WriteLine(ans);
            //
            int oneCounter = 0, prevDiff = 0, zeroCounter = 0;
            for(int i = 0; i < N; i++)
            {
                if (s[i] == '1' && oneCounter == 0)
                    oneCounter++;
                else if (s[i] == '1' && oneCounter == 1)
                {
                    oneCounter++;
                    prevDiff = zeroCounter;
                    zeroCounter = 0;
                }
                else if (s[i] == '1' && oneCounter == 2)
                {
                    if (prevDiff != zeroCounter)
                    {
                        ans = "NO";
                        break;
                    }
                    zeroCounter = 0;
                }
                else if (s[i] == '0' && oneCounter > 0)
                    zeroCounter++;
            }
            using (StreamWriter writer = new StreamWriter(@"output.txt"))
                writer.WriteLine(ans);
        }
    }
}


using System;
using System.IO;
using System.Text;

namespace Task_36A
{
    class Program
    {
        static void Main(string[] args)
        {
            //int N = int.Parse(Console.ReadLine());
            //string s = Console.ReadLine(), ans = "YES";
            string s, ans = "YES";
            int N;
            var fileStream = new FileStream(@"input.txt", FileMode.Open, FileAccess.Read);
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
            {
                N = int.Parse(streamReader.ReadLine());
                s = streamReader.ReadLine();
            }

                int prevDiff = -1, onePrevIndex = -1;
            for(int i = 0; i < N; i++)
            {
                if (s[i] == '1' && onePrevIndex == -1)
                    onePrevIndex = i;
                else if(s[i]=='1' && prevDiff == -1)
                {
                    prevDiff = i - onePrevIndex;
                    onePrevIndex = i;
                }
                else if (s[i] == '1')
                {
                    int currentDiff = i - onePrevIndex;
                    if(currentDiff != prevDiff)
                    {
                        ans = "NO";
                        break;
                    }
                    onePrevIndex = i;
                }
            }
            //Console.WriteLine(ans);
            using (StreamWriter writer = new StreamWriter(@"output.txt"))
                writer.WriteLine(ans);
        }
    }
}


package main
import "fmt"

func main(){
  var(
    s string
    i,j int
    old int = 0
    ok bool = true
  )
  fmt.Scanf("%s\n%s",&s,&s)
  for i=0;s[i]==byte('0')&&i<len(s);i++{}
  for i<len(s) {
    j = i
    for i++;i<len(s)&&byte('0')==s[i];i++ {}
    if i>=len(s) {
      break
    } else if 0!=old&&old!=i-j {
      ok=false
      break
    }
    old=i-j
  }
  fmt.Print(map[bool]string{true:"YES\n",false:"NO\n"}[ok])
}


package main
import "fmt"
import "os"

func main(){
  var(
    s string
    i,j int
    old int = 0
    ok bool = true
  )
  fin,_:=os.Open("input.txt")
  fout,_:=os.Create("output.txt")
  defer func(){
    fin.Close()
    fout.Close()
  }()
  fmt.Fscanf(fin,"%s\n%s",&s,&s)
  for i=0;s[i]==byte('0')&&i<len(s);i++{}
  for i<len(s) {
    j = i
    for i++;i<len(s)&&byte('0')==s[i];i++ {}
    if i>=len(s) {
      break
    } else if 0!=old&&old!=i-j {
      ok=false
      break
    }
    old=i-j
  }
  fmt.Fprint(fout,map[bool]string{true:"YES\n",false:"NO\n"}[ok])
}


package main
import "fmt"
import "os"

func main(){
  var(
    s string
    i,j int
    old int = 0
    ok bool = true
  )
  fmt.Scanf("%s\n%s",&s,&s)
  for i=0;s[i]==byte('0')&&i<len(s);i++{}
  for i<len(s) {
    j = i
    for i++;i<len(s)&&byte('0')==s[i];i++ {}
    if i>=len(s) {
      break
    } else if 0!=old&&old!=i-j {
      ok=false
      break
    }
    old=i-j
  }
  fmt.Print(map[bool]string{true:"YES\n",false:"NO\n"}[ok])
  os.Exit(0)
}


package main
import "fmt"

func main(){
  var(
    s string
    i,j int
    old int = 0
    ok bool = true
  )
  fmt.Scanf("%s\n%s",&s,&s)
  for i=0;byte(s[i])=='0'&&i<len(s);i++{}
  for i<len(s) {
    j = i
    for i++;i<len(s)&&byte('0')==s[i];i++ {}
    if i>=len(s) {
      break
    } else if 0!=old&&old!=i-j {
      ok=false
      break
    }
    old=i-j
  }
  fmt.Print(map[bool]string{true:"YES\n",false:"NO\n"}[ok])
}


package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
)

func main() {
    file, err := os.Open("input.txt")

    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    resp, errC := os.Create("output.txt")
    if errC != nil {
        log.Fatal(errC)
    }
    defer resp.Close()

    scanner := bufio.NewScanner(file)
    var i int = 0;
    var n , m string
    for scanner.Scan() {
        if(i == 0){
            n = scanner.Text()
        }else if(i == 1){
            m = scanner.Text()
            break;
        }
        i++;
    }

    var x int;
    nInt, err := strconv.Atoi(n)
    var varS int = 0
    var aux0 int = 0
    var flag bool = false;
    var first bool = true;
    var count bool = false;
    for x = 0; x < nInt; x++{
        if(m[x:x+1] == "1"){
            if(count){
                if(first){
                    varS = aux0
                    first = false
                }else{
                    if(varS != aux0){
                        _, err := resp.WriteString("NO");
                        _ = err
                        fmt.Println("output.txt")
                        return;
                    }
                }
                aux0 = 0;
            }else{
                count = true
            }
            flag = true;
        }else{
            if(flag){
                count = true
                aux0++
            }
        }

    }
     _, errF := resp.WriteString("YES");
        _ = errF
        fmt.Println("output.txt")

}


package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strings"
    "strconv"
)

func main() {
    file, err := os.Open("input.txt")

    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    resp, errC := os.Create("output.txt")
    if errC != nil {
        log.Fatal(errC)
    }
    defer resp.Close()

    scanner := bufio.NewScanner(file)
    var i int = 0;
    var n , m string
    for scanner.Scan() {
        if(i == 0){
            n = scanner.Text()
        }else if(i == 1){
            m = scanner.Text()
            break;
        }
        i++;
    }

    t := strings.Split(m, "1")
    var dim int = len(t)
    var x, y int;
    nInt, err := strconv.Atoi(n)
    if(dim<4) || nInt != len(m){
         _, err := resp.WriteString("NO");
         _ = err
         fmt.Println("output.txt")
    }else{
        y = len(t[1])
        for x = 2  ; x < dim-2 ; i++ {
            if(y != len(t[x])){
                _, errN := resp.WriteString("NO");
                _ = errN
                fmt.Println("output.txt")
                return;
            }
        }
        _, errF := resp.WriteString("YES");
        _ = errF
        fmt.Println("output.txt")
    }

}


<?php
    $in = fopen("input.txt", 'r');
    $out = fopen("output.txt", 'w');

    $i=0;
    while (!feof($in)) {
        $get[++$i] = fgets($in);
    }

    $get = explode("\n", implode("", $get));

    $n = $get[0];

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else if($signals[$i]=="1"){
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($out, "NO");
                    return;
                }
            }
        }
    }

    fputs($out, "YES");
?>


<?php
    $in = fopen("input.txt", 'r');
    $out = fopen("output.txt", 'w');

    $i=0;
    while (!feof($in)) {
        $get[++$i] = fgets($in);
    }

    $get = explode("\n", implode("", $get));

    $n = $get[0];
    $signals = $get[1];

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else {
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($out, "NO");
                    return;
                }
            }
        }
    }

    fputs($out, "YES");
?>


<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');

    $n = fgets($stdin);
    $signals = fgets($stdin);

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else {
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($stdout, "NO");
                    return;
                }
            }
        }
    }

    fputs($stdout, "YES");
?>


<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $get = explode("\n", file_get_contents("input.txt"));

    $signals = $get[0];
    $n = $get[1];

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else {
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($stdout, "NO");
                    return;
                }
            }
        }
    }

    fputs($stdout, "YES");
?>


<?php
    $stdin = fopen("input.txt", 'r');
    $stdout = fopen('php://stdout', 'w');

    $i=0;
    while (!feof($stdin)) {
        $get[++$i] = fgets($stdin);
    }

    $get = explode("\n", implode("", $get));

    $n = $get[0];
    $signals = $get[1];

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else {
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($stdout, "NO");
                    return;
                }
            }
        }
    }

    fputs($stdout, "YES");
?>


<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');

    $n = fgets($stdin);
    $signals = (string)fscanf($stdin, "r");

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else {
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($stdout, "NO");
                    return;
                }
            }
        }
    }

    fputs($stdout, "YES");
?>


<?php
    $in = fopen("input.txt", 'r');
    $out = fopen("output.txt", 'w');

    $i=0;
    while (!feof($in)) {
        $get[++$i] = fgets($in);
    }

    $get = explode("\n", implode("", $get));

    $n = $get[0];
    $signals = $get[1];

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else if($signals[$i]=="1"){
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($out, "NO");
                    return;
                }
            }
        }
    }

    fputs($out, "YES");
?>


<?php
    $stdin = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');

    $n = (string)fscanf($stdin, "r");
    $signals = (string)fscanf($stdin, "r");

    $interval = -1;
    $zeros = 0;
    $count_now=false;
    for($i=0;$i<$n;++$i){
        if($signals[$i]=="0")$zeros++;
        else {
            if($count_now==false){
               $count_now=true;
               $zeros=0;
            }
            else{
                if($interval==-1){
                    $interval = $zeros;
                    $zeros=0;
                }
                else if($zeros!=$interval){
                    fputs($stdout, "NO");
                    return;
                }
            }
        }
    }

    fputs($stdout, "YES");
?>