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

typedef pair<int,int> P;

int hoge(int i,int x,int ans){
    for (int i = 1; i < x; i++){
        ans /= 10;
    }
    return i %(ans*10) /ans;
}

int main(){
    int n,m;
    cin >> n >> m;
    vector<int>s(m); vector<int>c(m);
    for (int i = 0; i < m; i++){
        cin >> s.at(i) >> c.at(i);
    }
    if (n == 1){
        bool re0 = true;
        for (int i = 0; i < m; i++){
            if (c.at(i) != 0){
                re0 = false;
            }
        }
        if (re0){
            cout << 0 << "\n";
            return 0;
        }
    }
    int ans = 1;
    for (int i = 1; i < n; i++){
        ans *= 10;
    }
    if (m == 0){
        cout << ans << "\n";
        return 0;
    }
    for (int i = ans; i < ans*10; i++){
        bool ok = true;
        for (int j = 0; j < m; j++){

            if (hoge(i,s.at(j),ans) != c.at(j)){
                ok = false;
            }

        }
        if (ok){
            cout << i << "\n";
            return 0;
        }
    }
    cout << -1 << "\n";
}


#include<iostream>
#include<vector>
#include<math.h>

int main(){
    int N, M;
    std::cin >> N >> M;
    std::vector< int > s(M);
    std::vector< int > c(M);
    for(int i=0; i<M; i++){
        std::cin >> s[i] >> c[i];
    }

    int begin = 1;
    int end = 10;
    for(int i=1; i<N; i++){
        begin *= 10;
        end *= 10;
    }

    int ans = -1;
    for(int i=begin; i<end; i++){
        bool F = true;
        for(int j=0; j<M; j++){
            if( (int)((i % (int)pow(10, 4 - s[j]) ) / (int)pow(10, 4 - s[j] - 1) ) != c[j] ){
                F = false;
                break;
            }
        }
        if(F){
            ans = i;
            break;
        }
    }
    std::cout << ans << std::endl;

}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

If there is an integer not less than 0 satisfying the following conditions, print the smallest such integer; otherwise, print -1.

The integer has exactly N digits in base ten. (We assume 0 to be a 1-digit integer. For other integers, leading zeros are not allowed.)

The s_i-th digit from the left is c_i. \left(i = 1, 2, \cdots, M\right)

Constraints

All values in input are integers.

1 \leq N \leq 3

0 \leq M \leq 5

1 \leq s_i \leq N

0 \leq c_i \leq 9

Input

Input is given from Standard Input in the following format:

N M
s_1 c_1
\vdots
s_M c_M

Output

Print the answer.

Sample Input 1

3 3
1 7
3 2
1 7

Sample Output 1

702

702 satisfies the conditions - its 1-st and 3-rd digits are 7 and 2, respectively - while no non-negative integer less than 702 satisfies them.

Sample Input 2

3 2
2 1
2 3

Sample Output 2

-1

Sample Input 3

3 1
1 0

Sample Output 3

-1

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<string>
#include<queue>
#include<tuple>
#include<utility>
#include<functional>
#include<algorithm>

#define LL long long

using namespace std;

int n,m,ans[5];
bool err=false;

int main() {
	cin>>n>>m;
	for(int i=0;i<n;i++)ans[i]=-1;
	for(int i=0;i<m;i++){
		int s,c;
		cin>>s>>c;
		if(n!=1&&s==1&&c==0)err=true;
		if(ans[s-1]!=-1&&ans[s-1]!=c)err=true;
		ans[s-1]=c;
	}
	for(int i=0;i<n;i++){
		if(n!=1&&i==0)ans[i]=max(ans[i],1);
		else ans[i]=max(ans[i],0);
	}
	if(err)cout<<-1<<endl;
	else {
		for(int i=0;i<n;i++)cout<<ans[i];
		cout<<endl;
	}
	return 0;
}


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

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

#define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)

#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>

#define ll long long
#define ld long double
#define pb(a) push_back(a)
#define eb(a) emplace_back(a)

#define xx first
#define yy second
#define mp make_pair
#define pll pair<ll,ll>
#define mll map<ll,ll>
#define vll vector<ll>
#define pdd pair<double,double>
#define ALL(v) (v).begin(), (v).end()

const ll MOD=1e9+7; ;
const ll inf=1e18;

#define MODSET(d) if ((d) >= MOD) d %= MOD;
#define MODNEGSET(d) if ((d) < 0) d = ((d % MOD) + MOD) % MOD;
#define put(x) cout<<#x<<" = "<<x<<endl;

ll power(ll a,ll n){
    ll ans=1;
    while(n){
        if(n&1)
            ans=(ans*a);
        n>>=1;
        a=(a*a);
    }
    return ans;
}

ll powerMod(ll a,ll n){
    ll ans=1;
    while(n){
        if(n&1)
            ans=(ans*a)%MOD;
        n/=2;
        a=(a*a)%MOD;
    }
    return ans;
}

ll powerMod1(ll a,ll n,ll mod){
    ll ans=1;
    while(n){
        if(n&1)
            ans=(ans*a)%mod;
        n>>=1;
        a=(a*a)%mod;
    }
    return ans;
}

ll lcm(ll a,ll b){
    return a*(b/__gcd(a,b));
}

ll sumdigit(ll n){
    ll sum=0;
    while(n){
        sum+=n%10;
        n=n/10;
    }
    return sum;
}

ll countSetBit(ll a){
    return __builtin_popcount(a);
}
ll countBit(ll a){
    ll sum=0;
    while(a){
        sum++;
        a>>=1;
    }
    return sum;
}

ll length(ll a){
    ll ans=0;
    while(a){
        ans++;
        a=a/10;
    }
    return ans;
}

bool isVowel(char c){
	if(c=='a' or c=='e' or c=='i' or c=='o' or c=='u')
		return true;
	return false;
}

int main()
{
    fast;
    ll t;
    //~ cin>>t;
    t=1;
    while(t--){
			ll n,m;
			cin>>n>>m;
			bool yeah=true;
			string s;
			map<int,int>mp;
			for(int i=0;i<n;i++){
				s+="0";
			}
			for(int i=0;i<m;i++){
				int k,c;
				cin>>k>>c;
				if(k==1 and c==0 and n>1){
					yeah=false;
				}else if(mp[k-1]==0){
					mp[k-1]++;
					s[k-1]=(char)(c+'0');
				}else if(mp[k-1]){
					if(s[k-1]-'0'!=c){
						yeah=false;
					}
				}
			}
			if(yeah){
				if(s[0]=='0')
					s[0]='1';
				cout<<s;
			}else cout<<-1;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

const int maxV = 90010;
const int maxN = 3e2+10;
const int inf = 0x3f3f3f3f;
const ll MOD = 1e9+7;
const ll INF = 1000000000000000010LL;
#define X first
#define Y second

int a[maxN][maxN];
int c[maxN][maxN];
int b[maxN];
int d[maxN];
int main() {
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
		d[i] = -1;
	}
	for(int i=1;i<=m;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		if(d[x] == -1)
			d[x] = y;
		else if(d[x] != y)
		{
			puts("-1");
			return 0;
		}
	}
	if(d[1] == -1)
	{
		d[1] = 1;
	}
	else if(d[1] == 0)
	{
		puts("-1");
		return 0;
	}
	for(int i=1;i<=n;i++)
	{
		if(d[i] == -1)
			d[i] = 0;
	}
	int ans = 0;
	for(int i=1;i<=n;i++)
	{
		ans = ans*10 + d[i];
	}
	cout<<ans<<endl;
	return 0;
}


#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
    int first,second,third;
    first=second=third=-1;
    int n,m;
    scanf("%d%d",&n,&m);
    bool check=true;
    while(m--)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        if(a==1)
        {
            if(first!=-1)
            {
                if(first!=b)
                    check=false;
            }
            else
                first=b;
        }
        if(a==2)
        {
            if(second!=-1)
            {
                if(second!=b)
                    check=false;
            }
            else
                second=b;
        }
        if(a==3)
        {
            if(third!=-1)
            {
                if(third!=b)
                    check=false;
            }
            else
                third=b;
        }
    }
    if(first==0||!check)
        puts("-1");
    else
    {
        printf("%d",first==-1?1:first);
        printf("%d",second==-1?0:second);
        printf("%d\n",third==-1?0:third);
    }
    return 0;
}


#include<iostream>
#include<numeric>
#include<math.h>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<climits>
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>
#define ll long long
#define mkp make_pair
#define pll pair<ll,ll>
#define rep(i,from,to) for(int i=from;i<to;i++)
#define repd(i,from,till) for(int i=from;i>=till;i--)
#define waste ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define inf 1e9+1
#define mod 1e9+7
#define inf1 1e18+1
#define pie 3.14159265358979323846
#define N 100005
using namespace std;
/*
ll bin(ll i,ll j){
	ll mid=(i+j)/2;
	if(a[mid]==x)reutrn mid;
	else if(ans>x)return bin(i,mid-1);
	else return bin(mid+1,j);
}/*
ll power(ll base,ll power){
    ll res=1;
    base=base%mod;
    while(power>0){
    	if(power&1){
    		res=(res*base)%mod;
		}
		power=power>>1;
		base=(base*base)%mod;
	}
	return res;
}
*/
/*
int nCr(int x, int y){
	if(y>x)return 0;
	int num=fact[x];
	num*=invfact[y];
	num%=mod;
	num*=invfact[x-y];
	num%=mod;
	return num;
}
*/
/*bool prime[n+1];
void SieveOfEratosthenes(int n){
	rep(i,0,n+1)prime[i]=true
    for (int p=2;p*p<=n;p++)
        if (prime[p])
            for (int i=p*p;i<=n;i+=p)prime[i]=false;
}*/
/*
int gcd(int a,int b){
	if(b==0)return a;
	else return gcd(b,a%b);
}
*/
int solve(){
    int n,m;
    cin>>n>>m;
	int a[n];
	rep(i,0,n)a[i]=-1;
	rep(i,0,m){
		int b,c;
		cin>>b>>c;
		if(a[b-1]!=-1&&c!=a[b-1])return cout<<"-1"<<endl,0;
		a[b-1]=c;
	}
	rep(i,0,n){
		if(a[i]==-1)cout<<"0";
		else cout<<a[i];
	}
	cout<<endl;
	return 0;
}
int main(){
    waste;
    int t;
    //cin>>t;
    t=1;
    while(t--){
       	solve();
    }
}


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<int> v(n, -1);
    for (int i = 0; i < m; i++) {
        int s, c;
        cin >> s >> c;
        s--;
        if (v[s] >= 0 && v[s] != c) {
            cout << -1 << endl;
            return 0;
        }
        v[s] = c;
    }

    if (v[0] < 0)v[0] = 1;
    if (v[0] == 0) {
        if (n == 1)cout << 0 << endl;
        else cout << -1 << endl;
        return 0;
    }
    int ret = 0;
    for (int i = 0; i < n; i++) {
        ret *= 10;
        ret += max(0, v[i]);
    }

    cout << ret << endl;
    return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <queue>
#include <map>
#include <numeric>
#include <unordered_map>
#include <iomanip>
#include <functional>
#include <bitset>
#include <complex>
#include <stack>
#include <cstdint>

#define rep(i, n) for(ll i = 0; i < (ll)(n); i++)
#define rrep(i, n) for(ll i = (ll)(n-1); i >= 0; i--)
#define repi(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rrepi(i,a,b) for(ll i=(ll)(b-1);i>=(ll)(a);i--)

#define all(x) (x).begin(),(x).end()

template<class T>inline bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>inline bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

typedef long long ll;

using namespace std;

ll n,k;
vector<ll>a;
ll lo(ll num,ll d){
  ll mo=num%d;
  if(mo<0)mo+=d;
  return (num-mo)/d;
}
ll hi(ll num,ll d){

  ll mo=num%d;
  if(mo<0)mo+=d;
  if(mo!=0)mo-=d;
  return (num-mo)/d;
}
bool check(ll num){//numがkばんめ以降か
  ll cnt=0;//numより小さいもの
  rep(i,n){
    if(a[i]==0){
      if(0ll<num)cnt+=n-1-i;
      continue;
    }
    if(a[i]>0){
      ll tn=hi(num,a[i]);
      ll id=lower_bound(all(a),tn)-a.begin();
      cnt+=max(0ll,id-i-1);
    }
    else {
      ll tn=lo(num,a[i]);
      ll id=upper_bound(all(a),tn)-a.begin();
      cnt+=max(0ll,n-max(i+1,id));
    }
  }
  //cout<<cnt<<" "<<num<<endl;
  return cnt>=k;
}
int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin>>n>>k;
  a.resize(n);
  rep(i,n)cin>>a[i];
  sort(all(a));
  ll ng=-(ll)1e18-7,ok=(ll)1e18+7;

  while(abs(ok-ng)>1){
    ll mid=(ok+ng)/2;
    if(check(mid))ok=mid;
    else ng=mid;
  }
  cout<<ng<<endl;

  return 0;

}

Score: 400 points

Problem Statement

We have N integers A_1, A_2, ..., A_N.

There are \frac{N(N-1)}{2} ways to choose two of them and form a pair. If we compute the product of each of those pairs and sort the results in ascending order, what will be the K-th number in that list?

Constraints

All values in input are integers.

2 \leq N \leq 2 \times 10^5

1 \leq K \leq \frac{N(N-1)}{2}

-10^9 \leq A_i \leq 10^9\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the answer.

Sample Input 1

4 3
3 3 -4 -2

Sample Output 1

-6

There are six ways to form a pair. The products of those pairs are 9, -12, -6, -12, -6, 8.

Sorting those numbers in ascending order, we have -12, -12, -6, -6, 8, 9. The third number in this list is -6.

Sample Input 2

10 40
5 4 3 2 -1 0 0 0 0 0

Sample Output 2

6

Sample Input 3

30 413
-170202098 -268409015 537203564 983211703 21608710 -443999067 -937727165 -97596546 -372334013 398994917 -972141167 798607104 -949068442 -959948616 37909651 0 886627544 -20098238 0 -948955241 0 -214720580 277222296 -18897162 834475626 0 -425610555 110117526 663621752 0

Sample Output 3

448283280358331064


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 200000 + 5;
int to;
int n;
ll k;
int a[N];

ll cmp(ll val) {
	int p=to+1;
	ll cnt=0;
	for(int i=to;i>=1 && p<=n;i--) {
		while(val<0 && p<=n && abs((ll)a[i]*a[p])<abs(val)) p++;
		cnt+=max(0,n-p+1);
	}
	return cnt;
}

ll in(int l,int r,ll val) {
	int p=r;
	ll cnt=0;
	for(int i=l;i<p;i++) {
		while(p>0 && (ll)a[i]*a[p]>val) p--;
		cnt+=max(0,p-i);
	}
	return cnt;
}

ll cnt(ll val) {
	return in(1,to,val)+in(to+1,n,val)+cmp(val);
}

int main() {
	cin >> n >> k;
	for(int i = 1; i <= n; i++)
		cin >> a[i];
	sort(a+1,a+n+1);
	for(to = 1; to <= n; to++)
		if(a[to] >= 0)
			break;
	reverse(a+1,a+to);
	to--;
	ll l = -(ll)inf*inf,r = -l;
	while(l <= r){
		ll mid = (l+r)>>1;
		if(cnt(mid) >= k)
			r = mid-1;
		else
			l = mid+1;
	}
	cout << l << endl;
}


//#pragma GCC optimize ("Ofast")
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC target("avx,avx2,fma")

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
#define pb push_back
#define F first
#define S second
#define ins insert
#define mp make_pair
#define fo(i, n1, n, x) for(int i = n1; i <= n; i += x)
#define foo(i, n, n1, x) for(int i = n; i >= n1; i -= x)
#define bit __builtin_popcount
#define md (l + ((r - l) / 2))
#define all(x) x.begin(),x.end()
#define eb emplace_back
#define ub upper_bound
#define lb lower_bound
#define ios ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

using ll = long long;

#define int ll

const int N = 2e5 + 11, mod = 1e9 + 7, mod2 = 998244353;
const int MAX = 1e5 + 11;
const int INF1 = 2e9 + 11;
const ll INF2 = 2e18 + 11;
const double INF3 = 1e8 + 11;
const int base = 500;
const int P = 31;
const int dx[] = {1, -1, 0, 0, 1, 1, -1, -1};
const int dy[] = {0, 0, 1, -1, 1, -1, 1, -1};
const double EPS = 1e-4;
const double PI = acos(-1.0);

template<typename T> using ordered_set = tree <T, null_type, less <T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; }
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; }

typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int n, k;
main() {
    file("threesum");
    ios;
    cin >> n >> k;

    vi v;
    int zr = 0;
    for (int i = 0; i < n; ++i) {
        int x;
        cin >> x;
        if (x) v.eb(x);
        else ++zr;
    }

    n = v.size();
    sort(all(v));

    int l = -INF2, r = INF2;

    auto f = [&](int x) {
        int cnt = 0;
        if (0 < x) cnt += n * zr * 2 + zr * (zr - 1);
        for (int i = 0; i < n; ++i) {
            if (v[i] > 0) {
                if (v[0] * v[i] >= x) continue;
                int L = 0, R = n - 1;
                while (L <= R) {
                    int mid = (L + ((R - L) >> 1));
                    if (v[i] * v[mid] < x) L = mid + 1;
                    else R = mid - 1;
                }
                --L;
                int y = L;
                if (i <= L) --L;
                cnt += L + 1;

            } else {
                if (v[i] * v[n - 1] >= x) continue;
                int L = 0, R = n - 1;
                while (L <= R) {
                    int mid = (L + ((R - L) >> 1));
                    if (v[i] * v[mid] < x) R = mid - 1;
                    else L = mid + 1;
                }
                ++R;
                R = n - R;
                if (v[i] * v[i] < x) --R;
                cnt += R;
            }
        }
        cnt>>=1;
        return cnt;
    };

    while (l <= r) if (f(md) >= k) r = md - 1; else l = md + 1;

    cout<<l-1;
    cerr << "\nTime elapsed: " << (clock() + 0.0) / CLOCKS_PER_SEC;
    return 0;
}
/**
10 40
5 4 3 2 -1 0 0 0 0 0

-4 -2 3 3

-12 -12 -6 -6

*/


#include <algorithm>
#include <iostream>
#include <vector>

using ll = long long int;
using namespace std;

int main(){
    int n, k; cin >> n >> k;
    vector<ll> pluss;
    vector<ll> minuss;
    vector<ll> zeros;
    for(int i=0; i<n; ++i){
        ll a; cin >> a;
        if(a < 0){ minuss.push_back(a); }
        else if(a == 0){ zeros.push_back(a); }
        else{ pluss.push_back(a); }
    }
    sort(pluss.begin(), pluss.end());
    sort(minuss.begin(), minuss.end());

    ll p_len = pluss.size();
    ll m_len = minuss.size();
    ll z_len = zeros.size();

    ll minus_num = p_len * m_len;
    ll zeros_num = z_len * (z_len - 1) / 2 + z_len * (m_len + p_len);

    ll l = -(ll)1e18 - 10LL; ll r = (ll)1e18 + 10LL;
    while(r - l > 1LL){
        ll mid = (l + r) / 2LL;
        ll cnt = 0;
        if(mid > 0LL){
            ll ret = 0;
            for(int i=0; i<(int)pluss.size(); ++i){
                ret += upper_bound(pluss.begin(), pluss.end(), mid / pluss[i]) - pluss.begin();
                if(pluss[i] * pluss[i] <= mid){ ret -= 1LL; }
            }
            cnt += ret / 2LL;
            ret = 0;
            for(int i=0; i<(int)minuss.size(); ++i){
                ret += m_len - (int)(lower_bound(minuss.begin(), minuss.end(), mid / minuss[i]) - minuss.begin());
                if(minuss[i] * minuss[i] <= mid){ ret -= 1LL; }
            }
            cnt += ret / 2LL;
            cnt += minus_num;
            cnt += zeros_num;
        }
        else if(mid == 0LL){
            cnt += minus_num;
            cnt += zeros_num;
        }
        else{
            for(int i=0; i<(int)pluss.size(); ++i){
                cnt += upper_bound(minuss.begin(), minuss.end(), (mid - pluss[i] + 1) / pluss[i]) - minuss.begin();
            }
        }
        if (cnt >= k){
            r = mid;
        }
        else{
            l = mid;
        }
    }
    cout << r << endl;
}


#include<bits/stdc++.h>
using namespace std;
namespace io{
    const int l=1<<20;
    char buf[l],*s,*t,c;
    inline void gc(){
        if(s==t){
            t=(s=buf)+fread(buf,1,l,stdin);
            c=s==t?EOF:*s++;
        }else c=*s++;
    }
    template<class IT>inline void gi(IT &x){
        x=0;gc();while(c<'0'||c>'9')gc();
        while('0'<=c&&c<='9'){x=(x<<1)+(x<<3)+(c^48);gc();}
    }
    char buf0[20];int a;
    template<class IT>inline void pi(IT x){
        if(x<0){putchar('-');x=-x;}
        do buf0[++a]=x%10+48;while(x/=10);
        while(a)putchar(buf0[a--]);
        putchar('\n');
    }
};
using io::gi;
using io::pi;
typedef unsigned int ui;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<int,ll > pil;
typedef pair<ll ,int> pli;
typedef pair<ll ,ll > pll;
#define pque priority_queue
#define rep(i,l,r) for(i=(l);i<=(r);++i)
#define per(i,l,r) for(i=(l);i>=(r);--i)
#define REP(i,l,r) for(i=(l);i< (r);++i)
#define PER(i,l,r) for(i=(l);i> (r);--i)
#define mp make_pair
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define fi first
#define se second
template<class IT>inline void cmax(IT &a,IT b){if(a<b)a=b;}
template<class IT>inline void cmin(IT &a,IT b){if(b<a)a=b;}
const int N=200005;
ll a[N],b[N],z;int A,B;
inline ll C2(int x){return ((ll)x)*(x-1);}
ll solve(ll m){
	int i;
	if(m<0ll){
		ll s=0ll;
		m=-(m+1ll);
		rep(i,1,A)s+=(b+B+1)-upper_bound(b+1,b+B+1,m/a[i]);
		return s;
	}else{
		ll s=0ll;
		rep(i,1,B)s+=upper_bound(b+1,b+B+1,m/b[i])-(b+1);
		rep(i,1,A)s+=upper_bound(a+1,a+A+1,m/a[i])-(a+1);
		rep(i,1,A)if(a[i]*a[i]<=m)--s;
		rep(i,1,B)if(b[i]*b[i]<=m)--s;
		//printf("solve m=%lld s=%lld z=%lld\n",m,s,z);
		return (s>>1)+z;
	}
}
int main(){
    //freopen("a.in","r",stdin);
    //freopen("a.out","w",stdout);
    int n;ll x,cn,k,l=-1000000000000000000ll,r=1000000000000000000ll,m,s;
    scanf("%d%lld",&n,&k);cn=C2(n);
    while(n--){
		scanf("%lld",&x);
		if(x){
			if(x>0)a[++A]=x;
			else b[++B]=-x;
		}
	}
	//printf("%lld - %lld - %lld\n",cn,C2(A),C2(B));
	z=(cn-(C2(A)+C2(B)))>>1;
	sort(a+1,a+A+1);
	sort(b+1,b+B+1);
	while(l<=r){
		m=(l+r)>>1;
		if(solve(m)<k)l=m+1ll;
		else r=(s=m)-1ll;
	}
	printf("%lld",s);
    return 0;
}


#include <bits/stdc++.h>

using namespace std;
using i64 = int64_t;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(), (x).end()
const int INF = (1 << 30);
const i64 INFL = (1LL << 62);
const i64 MOD = 1000000007;

bool check(i64 x, i64 k, const vector<i64> &a) {
  // x 以下の数がk個以上ある？
  i64 cnt = 0;  // x以下の数の個数
  i64 n = a.size();

  rep(i, n) {
    i64 ci = 0;
    double t = 0;
    if (a[i] == 0) {
      // 0とかけてx以下になる個数
      if (x < 0) {
      } else {
        ci = n - 1 - i;
      }
    } else {
      t = x / a[i];
      if (a[i] > 0) {
        // t以下の数の個数
        ci = upper_bound(a.begin() + i + 1, a.end(), t) - (a.begin() + i + 1);
      } else {
        // t以上の数の個数
        ci = a.end() - lower_bound(a.begin() + i + 1, a.end(), t);
      }
    }
    cnt += ci;
    // cout << "a[i]:" << a[i] << ", x:" << x << ", t:" << t << ", ci:" << ci
    //      << endl;
  }

  return cnt >= k;
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  i64 n, k;
  cin >> n >> k;
  vector<i64> a(n);
  rep(i, n) { cin >> a[i]; }
  sort(all(a));
  const i64 MAX = 1e18 * 2;
  i64 ok = MAX;
  i64 ng = -MAX;
  while (abs(ok - ng) > 1) {
    i64 mid = (ok + ng) / 2;
    if (check(mid, k, a)) {
      ok = mid;
    } else {
      ng = mid;
    }
  }
  cout << ok << endl;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

int n;
long long k;
vector<long long> v;
vector<long long> vpos;

bool check(long long x) {
    long long cnt = 0;
    if (v[0] < 0) {
        int i = 0;
        int j;
        for (j = 0; j < n; j++) {
            if (v[j] * v[i] <= x) {
                break;
            }
        }
        while (i >= j) {
            j++;
        }
        cnt += n-j;
        for (i = 1; i < n; i++) {
            if (v[i] >= 0) {
                break;
            }
            while (j > i && v[i] * v[j] <= x) {
                j--;
            }
            j++;
            while (i >= j) {
                j++;
            }
            cnt += n-j;
            //cnt += n-j;
            //if (i >= j) {
            //    cnt--;
            //}
        }
    }
    //cout << "negcnt " << cnt  << endl;
    int np = vpos.size();
    if (np > 0) {
        int i = np-1;
        int j;
        for (j = np-1; j >= 0; j--) {
            if (vpos[j] * vpos[i] <= x) {
                break;
            }
        }
        while (i <= j) {
            j--;
        }
        cnt += j+1;
        //cout << v[i] << " add " << j+1 << endl;
        for (i = np-2; i >= 0; i--) {
            if (vpos[i] < 0) {
                break;
            }
            while (j < i && vpos[i] * vpos[j] <= x) {
                j++;
            }
            j--;
            while (i <= j) {
                j--;
            }
            cnt += j+1;
            //cout << v[i] << " add " << j+1 << endl;
            //cnt += j+1;
            //if (i <= j) {
            //    cnt--;
            //}
        }
    }
    //cout << "HAD " << cnt << " of " << k << endl;
    return cnt >= k;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin >> n;
    cin >> k;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        v.push_back(x);
    }
    sort(v.begin(), v.end());
    for (int i = 0; i < n; i++) {
        if (v[i] >= 0) {
            vpos.push_back(v[i]);
        }
    }

    long long INF = 2e18;
    long long l = -INF;
    long long r = INF;
    while (l+1 != r) {
        long long mid = (l+r)/2;
        //cout << l << " " << r << " " << mid << endl;
        if (check(mid)) {
            r = mid;
        } else {
            l = mid;
        }
    }
    cout << r << endl;

    return 0;
}


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

// マクロ //
#define rep(i,N) for(int i = 0; i < N; i++)
#define all(x) x.begin(), x.end()
#define sort(x) sort(all(x))
#define cou(x) cout << x << endl
#define y() cout << "Yes" << endl
#define n() cout << "No" << endl
#define Y() cout << "YES" << endl
#define N() cout << "NO" << endl
#define x2(x) (x) * (x)

// 型エイリアス //
using lint = long long;
using vi = vector<int>;
using vli = vector<lint>;
using vc = vector<char>;
using vs = vector<string>;
using vb = vector<bool>;
using vvi = vector<vi>;
using pii = pair<int, int>;
using vpii = vector<pii>;
using msi = map<string, int>;

// 関数 //
int gcd(int a, int b) {
    int t;
    while (b != 0) {
        t = a % b;
        a = b;
        b = t;
    }
    return a;
}

int lcm(int a, int b) {
    return a * b / gcd(a, b);
}

double distance(pii a, pii b) {
    double dist;
    dist = sqrt(x2(a.first - b.first) + x2(a.second - b.second));
    return dist;
}

lint perm(int a) {
    lint perm = 1;
    for (int i = a; i >= 1; i--) {
        perm *= i;
    }
    return perm;
}

lint comb(int n, int m) {
    return perm(n) / (perm(n - m) * perm(m));
}

// End of Template //

int main() {

    int N , M;
    cin >> N >> M;

    cou((N < 10 && M < 10 ? N * M : -1));
}

Score : 100 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.

Given are two integers A and B.

If Takahashi can calculate A \times B, print the result; if he cannot, print -1 instead.

Constraints

1 \leq A \leq 20

1 \leq B \leq 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If Takahashi can calculate A \times B, print the result; if he cannot, print -1.

Sample Input 1

2 5

Sample Output 1

10

2 \times 5 = 10.

Sample Input 2

5 10

Sample Output 2

-1

5\times 10 = 50, but Takahashi cannot do this calculation, so print -1 instead.

Sample Input 3

9 9

Sample Output 3

81


#include <iostream>

using namespace std;

int main(void) {
    int A, B;
    cin >> A >> B;
    if(A > 9 || B > 9) {
        cout << -1 << endl;
    } else {
        cout << A*B << endl;
    }
    return 0;
}


#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {

  int A;
  int B;

  cin >> A;
  cin >> B;

  if (A > 9 || B > 9) {
    cout << "-1" <<endl;
  }else {
    cout << A*B << endl;
  }

  return 0;
}


#include <bits/stdc++.h>
#ifdef LOCAL_DEBUG
#define DEBUG 1
#define CERR if(DEBUG) cerr
#define MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,NAME,...) NAME
#define pr(...) CERR<<MACRO(__VA_ARGS__,pr10,pr9,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__)<<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
#define pr9(a,b,c,d,e,f,g,h,i) pr1(a)<<pr8(b,c,d,e,f,g,h,i)
#define pr10(a,b,c,d,e,f,g,h,i,j) pr1(a)<<pr9(b,c,d,e,f,g,h,i,j)
#define prArr(a){CERR<<(#a)<<"={";int i=0;for(auto t:(a))CERR<<(i++?", ":"")<<t;CERR<<"}"<<endl;}
#else
#define DEBUG 0
#define pr(...)
#define prArr(a)
#endif
using namespace std;
using Int = long long;
using _int = int;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";}
template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;}
template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;}
template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;}
//INSERT ABOVE HERE

signed main(){
  srand((unsigned)time(NULL));
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  Int A, B;
  cin>>A>>B;

  if(1 <= A && A <= 9 && 1 <= B && B <= 9) cout<<A * B<<endl;
  else cout<<-1<<endl;

  return 0;
}


#include<bits/stdc++.h>

int main(){
    using ll = long long;
    int K;
    std::string s;
    std::cin>>s>>K;
    ll dp[31]={};
    bool bk=true;
    for(int i=0;i+1<s.size();++i){
        if(s[i]==s[i+1]){
            dp[0]++;
            i++;
            if(i+1==s.size()) bk = false;
            if(i==0){
                bk = false;
                i--;
            }
        }
    }
    bk &= s.front()==s.back();
    ll ans=0;
    for(int i=0;i<=31;++i){
        if(i<31) dp[i+1] = 2*dp[i] + bk;
        if(K>>i&1) ans += dp[i];
    }
    std::cout<<ans<<"\n";
}

Score : 300 points

Problem Statement

Given is a string S. Let T be the concatenation of K copies of S.
We can repeatedly perform the following operation: choose a character in T and replace it with a different character.
Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different.

Constraints

1 \leq |S| \leq 100

S consists of lowercase English letters.

1 \leq K \leq 10^9

K is an integer.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the minimum number of operations required.

Sample Input 1

issii
2

Sample Output 1

4

T is issiiissii. For example, we can rewrite it into ispiqisyhi, and now any two adjacent characters are different.

Sample Input 2

qq
81

Sample Output 2

81

Sample Input 3

cooooooooonteeeeeeeeeest
999993333

Sample Output 3

8999939997


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int,int>;
#define rep(i,n) for(ll i = 0; i < (ll)(n); i++)
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
const ll INF = 1LL << 60;
int main(){
    string s;
    int k;
    cin >> s >> k;
    int tot = 0;
    int se = 1;
    int n = s.size();
    int a,b;
    bool start = true;
    rep(i,n){
        if(!i) continue;
        if(s[i]==s[i-1])se++;
        else {
            if(tot==0 && start) {
                a = se;
                start = false;
            }
            tot += se/2;
            se=1;
        }
    }
    b = se;
    tot += b/2;
    ll ans = (ll)tot*k;
    if(s[0]==s[n-1]){
        ans -= (a/2 + b/2)*(k-1);
        ans += ((a+b)/2)*(k-1);
    }
    cout << ans << endl;

    return 0;
}


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

ll f(string S){
  ll res=0;
  int i=1;
  while(1){
    if(i>=S.size())break;
    if(S[i-1]==S[i]){
      res++;
      i++;
    }
    i++;
  }
  return res;
}

int main(){
  string S;
  int K;
  cin >> S >> K;
  if(f(S+S)>f(S)*2){
    cout << f(S)*K+K-1 << endl;
    return 0;
  }else if(f(S+S)==f(S)*2){
    cout << f(S)*K << endl;
    return 0;
  }
}


#pragma gcc optimize("Ofast")
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(V) (V).begin(),(V).end()
#define SORT(V) sort(ALL(V)) //小さい方からソート
#define REV(V) reverse(ALL(V)) //リバース
#define RSORT(V) SORT(V);REV(V) //大きい方からソート
#define NPN(V) next_permutation(ALL(V)) //順列
#define pb(n) push_back(n)
#define endl '\n'
#define Endl '\n'
#define DUMP(x)  cout << #x << " = " << (x) << endl
#define YES(n) cout << ((n) ? "YES" : "NO"  ) << endl
#define Yes(n) cout << ((n) ? "Yes" : "No"  ) << endl
#define yes(n) cout << ((n) ? "yes" : "no"  ) << endl
#define Yay(n) cout << ((n) ? "Yay!": ":(") << endl
#define RAPID cin.tie(0);ios::sync_with_stdio(false)
#define VSUM(V) accumulate(ALL(V), 0)
#define MID(a,b,c) (a) < (b) && (b) < (c)
#define MIDe(a,b,c) (a) <= (b) && (b) <= (c)
#define IN(n) cin >> n
#define IN2(a,b) cin >> a >> b
#define IN3(a,b,c) cin >> a >> b >> c
#define IN4(a,b,c,d) cin >> a >> b >> c >> d
#define VIN(V) for(int i = 0; i < (V).size(); i++) {cin >> (V).at(i);}
#define OUT(n) cout << n << endl
#define VOUT(V) REP(i, (V).size()) {cout << (V)[i] << endl;}
#define VOUT2(V) REP(i, (V).size()) {cout << (V)[i] << " ";} cout<<endl;

// 型マクロ定義
#define int long long
#define P pair<ll,ll>
#define Vi vector<ll>
#define VVi vector<vector<ll>>
#define Vd vector<double>
#define Vb vector<bool>
#define Vs vector<string>
#define Vc vector<char>
#define M map<ll,ll>
#define S set<ll>
#define PQ priority_queue<ll>
#define PQG priority_queue<ll,V,greater<ll>
//

template<class T> inline bool chmin(T& a, T b) {if(a>b){a=b;return true;}return false;}
template<class T> inline bool chmax(T& a, T b) {if(a<b){a=b;return true;}return false;}

const int MOD = 1000000007;
const int INF = 1061109567;
const double EPS = 1e-10;
const double PI  = acos(-1.0);

int gcd(int a,int b){return b != 0 ? gcd(b, a % b) : a;} //最大公約数
int lcm(int a, int b){return a * b / gcd(a, b);}
string toStrUp(string str){char diff = 'A'-'a';REP(i,str.size()) str[i] += diff;return str;}
string gCh(string str, int key){return str.substr(key,1);}

signed main() {
  RAPID;
  // デフォルト変数定義
  int n=0,m=0,a=0,b=0,c=0,d=0,x=0,y=0,z=0;
  string s="",t="";
  //

  // ここから
  IN2(s,x);
  REP(i,s.size()-1){
    if(s[i]==s[i+1]){
      z++;
    }else{
      y += (z+1)/2;
      z = 0;
    }
  }
  if(s[0]==s[s.size()-1]){
    y++;
  }
  OUT(y*x);
}


//
//  main.cpp
//  ABC124
//
//  Created by hiroaki on 2019/05/07.
//  Copyright © 2019年 hiroaki. All rights reserved.
//

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <tuple>
#include <bitset>
#include <string>
// #include <sstream>
// #include <iomanip>
//pair sort firstに揃う

#define int long long
#define double long double
#define Rap(n,i) for(int (i)=0;(i)<(n);(i)++)
#define Pr(n) cout<<n<<endl;
#define PairV vector<pair<int , int> >
#define F first
#define S second
#define Vector1 vector<int>
#define VectorS vector<string>
#define vector2 vector<vector<int> >
#define index(v,x) find((v).begin(), (v).end(), (x))-(v).begin()
#define ctoi(c) (int)(c-'0')
#define incin(n) int (n); cin>>(n);
#define incin2(n,m) int (n),(m); cin >> (n)>>(m);
#define stcin(s) string (s); cin>>(s);
#define all(v) (v).begin() , (v).end()
namespace Mathf
{
    const int INF = 1000000000000;
    const double PI = 3.14159274;
    const double Rad2Deg = 57.29578;
    const double log2(double a,double b);
    const double log2(double a,double b){
        return log(b)/log(a);
    }
} // namespace Mathf

using namespace std;

int MD(pair<int,int> a,pair<int,int> b){//ManhattanDisRance
    return abs(a.first-b.first) + abs(a.second-b.second);
}
int MOD(int a,int b){
    return abs(a%b);
}
template <typename T1,typename T2> bool Comp (pair<T1,T2> a,pair<T1,T2> b){
    if(a.first!=b.first){
        return a.first<b.first;//first昇順
    }
    if(a.second!=b.second){
        return a.second > b.second;//second降順
    }else{
        return  true;
    }
}
double Dis(pair<int,int> a,pair<int,int> b){
    return sqrt((a.first-b.first)*(a.first-b.first)+(a.second-b.second)*(a.second-b.second));
}
int Step(int N){
    if(N==0){
        return 1;
    }else{
        return N*Step(N-1);
    }
}
int Pemu(int n,int r){
    int ans = n;
    for(int i=0;i<r;i++){
        ans*=(ans-i);
    }
    return ans;
}
int Comb(int n,int m){
    int ans=n;
    for(int i=0;i<m;m++){
        ans*=(ans-i);
    }
    return ans/Step(m);
}
int Digit(int x){
    string ss = to_string(x);
    int size = ss.size();
    int sum = 0;
    for(int i=0;i<size;i++){
        sum+=ctoi(ss[i]);
    }
    return sum;
}
class City{
    public:
        int num;
        int p;
        int n;
        int y;
        int id;
        City();
};
City::City(){
    num = 0;
    p=0;
    n=0;
    y=0;
    id=0;
}

signed  main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    // incin2(n,m);
    // vector<City> cities(m+1);
    // Rap(m,i){
    //     cities[i].num = i+1;
    //     cin >> cities.at(i).p >> cities.at(i).y;
    // }
    // sort(cities.begin(),cities.end()-1,[](const City &a,const City &b){
    //     if(a.p==b.p){
    //         return a.y<b.y;
    //     }else{
    //         return a.p<b.p;
    //     }
    // });
    // int log  = 1;
    // Rap(m,i){
    //     cities[i].n = log;
    //     log++;
    //     if(cities[i].p!=cities[i+1].p){
    //         log = 1;
    //     }
    // }
    // sort(cities.begin(),cities.end()-1,[](const City &a,const City &b){return a.num<b.num;});
    // Rap(m,i){
    //     stringstream ss;
    //     ss<<setw(6)<<setfill('0')<<cities[i].p<<setw(6)<<cities[i].n;
    //     cout<<ss.str()<<endl;
    // }
    stcin(s);
    incin(k);
    int flag = 0;
    Rap(s.size()-1,i){
        if(s[i+1]!=s[i]){
            flag = 1;
            break;
        }
    }
    int ans = 0;
    if(flag==0){
        cout<<s.size()*k/2<<endl;
    }else{
        int log = 0;
        if(s[0]!=s[s.size()-1]){
            Rap(s.size()-1,i){
                log ++;
                if(s[i+1]!=s[i]){
                    ans +=log/2;
                    log = 0;
                }
            }
            cout<<k*ans<<endl;
        }else{
            Rap(s.size()-1,i){
                log ++;
                if(s[i+1]!=s[i]){
                    ans +=log/2;
                    log = 0;
                }
            }
            ans = k*ans;
            int a = 1;
            Rap(s.size()-1,i){
                if(s[i]==s[i+1]){
                    a++;
                }else{
                    break;
                }
            }
            int b = 1;
            for(int i=s.size()-1;i >= 0;i--){
                if (s[i]==s[i-1])
                {
                    b++;
                }else{
                    break;
                }
            }
            ans *=k;
            ans -= (a/2+b/2-(a+b)/2) * (k-1);
            cout<<ans<<endl;
        }
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define ll long long int
#define ld long double
#define vi vector<int>
#define vl vector<ll>
#define v2i vector<vector<int>>
#define v2l vector<vector<ll>>
#define ppi pair<int,int>
#define vpi vector<ppi>
#define ppl pair<ll,ll>
#define all(x) x.begin(),x.end()
#define ii int,int
#define ff first
#define ss second
#define forn(i,a,b) for(int i=a;i<b;i++)
#define forr(i,a,b) for(int i=a;i>=b;i--)
#define forv(i,m) for(auto i : m)
#define imx INT_MAX
#define imn INT_MIN
#define inf LONG_MAX
#define minf LONG_MIN
#define endl "\n"
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);
#define sze size()
#define rvs reverse
#define itr iterator
#define pre cout<<fixed<<setprecision(10);
#define umap unordered_map
#define uset unordered_set
#define pi 3.141592653589793
const ll infinity = 9e18;

/*
#define MODM(a,b,md) ((a%md)*(b%md))%md
#define MODA(a,b,md) ((a%md)+(b%md))%md
#define ull unsigned long long int
#define si short int
*/

/*
bool compare(int a,int b) {return a > b;}
bool compare1(ppi a,ppi b) {return a.ff > b.ff;}
bool compare2(ppi a,ppi b) {return a.ss < b.ss;}
ll Npower(ll a,ll b) {ll product = 1; while(b){if(b&1){product = product*a;}a = a*a;b = b>>1;} return product;}
ll power(ll a,ll b,ll md) {ll product = 1; while(b){if(b&1){product = MODM(product,a,md);}a = MODM(a,a,md);b = b>>1;} return product%md;}
bool isprime(ll n){if(n < 2) return 0; ll i = 2; while(i*i <= n){if(n%i == 0) return 0; i++;} return 1;}
ll GCD(ll a,ll b) {return b==0 ? a:GCD(b,a%b);}
ll LCM(ll a,ll b) {return (a/GCD(a,b))*b; }
*/

int main()
{
    fast

    string str;
    cin>>str;

    ll n;
    cin>>n;

    map<int,int> m;
    forn(i,0,str.sze)
    {
        m[str[i]-'a']++;
    }

    if(m.sze == 1)
    {
        cout<<((n*((ll)str.sze))/2);
        return 0;
    }

    if(str[0] == str[str.sze-1])
    {
        ll a = 0;
        int i = 0;
        for(; i < str.sze; i++)
        {
            if(str[i] != str[0]) break;
        }

        a = i;

        ll b = 0;

        int j = str.sze-1;
        for(; j >= i; j--)
        {
            if(str[j] != str[0]) break;
        }

        b = str.sze-1-j;

        ll c = 0;

        for(; i < j; i++)
        {
            if(str[i] == str[i+1])
            {
                str[i+1] = '0';
                c++;
            }
        }

        ll total = a/2 + b/2 + ((a+b)/2)*(n-1) + n*c;
        cout<<total;

    }
    else
    {
        string s = str;
        ll total = 0;
        forn(i,0,s.sze-1)
        {
            if(s[i] == s[i+1])
            {
                s[i+1] = '0';
                total++;
            }
        }

        cout<<n*total;
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0, i##_len = (n); i < i##_len; i++)
#define reps(i, s, n) for(int i = (s), i##_len = (n); i < i##_len; i++)
#define rrep(i, n) for(int i = (n) - 1; i >= 0; i--)
#define rreps(i, e, n) for(int i = (n) - 1; i >= (e); i--)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((int)(x).size())
#define uniq(x) (x).erase(unique((x).begin(), (x).end()), (x).end())

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);

    string s;
    int k;
    cin >> s >> k;
    int sl = s.length();
    int fc = 0, lc = 0, cc = 0, nc = 0;
    bool bf = false;
    ll ans = 0;

    rep(i, sl) {
        if (s[0] == s[i]) {
            fc++;
        }
        else {
            break;
        }
    }

    rrep(i, sl) {
        if (s[0] == s[i]) {
            lc++;
        }
        else {
            break;
        }
    }

    if (fc == sl) {
        ans = (ll)sl * k / 2;
    }
    else {
        rep(i, sl - 1) {
            if ((!bf) && (s[i] == s[i + 1])) {
                cc++;
                bf = true;
            }
            else {
                bf = false;
            }
        }

        if ((fc % 2 == 1) && (lc % 2 == 1)) {
            nc++;
        }

        ans = (ll)cc * k + (ll)nc * (k - 1);
    }

    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define pr(...) cerr<< GET_MACRO(__VA_ARGS__,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__) <<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
#define prArr(a) {cerr<<(#a)<<"={";int i=0;for(auto t:(a))cerr<<(i++?", ":"")<<t;cerr<<"}"<<endl;}
using namespace std;
using Int = long long;
using _int = int;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";}
template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){
  return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;}
template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;}
template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;}
//INSERT ABOVE HERE

Int calc(string s, Int K){

  Int N = s.size();
  vector<vector<Int> > dp(K * N + 1, vector<Int>(3, INF)); //[回数 * 添字][前回の文字(0:同じ, 1:変えた)]

  dp[0][1] = 0;
  for(Int i=0;i<K * N;i++){
    {//k == 0
      if(i == 0 || s[i%N] != s[(i-1 + N)%N]) Min(dp[i+1][0], dp[i][0]); //変えない
      Min(dp[i+1][1], dp[i][0] + 1); //変える
    }
    {//k == 1
      Min(dp[i+1][0], dp[i][1]);
      Min(dp[i+1][1], dp[i][1]+1);
    }
  }
  Int res = min(dp[K * N][0], dp[K * N][1]);
  return res;
}

signed main(){
  srand((unsigned)time(NULL));
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  string s;
  cin>>s;

  Int K;
  cin>>K;

  if(K < 10){
    Int ans = calc(s, K);
    cout<<ans<<endl;
    return 0;
  }

  Int a = calc(s, 4);
  Int b = calc(s, 5);
  Int ans = a + (b - a) * (K - 4);
  cout<<ans<<endl;

  return 0;
}


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

int main(){
	string s; long long k;
	cin >> s >> k;
	string t = s,d = s;
	long long ans1 = 0,ans2 = 0,ans3 = 0;
	for(int i = 1;i < s.size();i++){
		if(s[i] == s[i-1]){
			ans1++;
			s[i] = '-';
		}
	}
	t = s + t;
	for(int i = 1;i < t.size();i++){
		if(t[i] == t[i-1]){
			ans2++;
			t[i] = '-';
		}
	}
	d = t + d;
	for(int i = 1;i < d.size();i++){
		if(d[i] == d[i-1]){
			ans3++;
			d[i] = '-';
		}
	}
	long long sum = ans1 + (ans2 + ans3) * ((k-1)/2);
	if((k-1)%2 == 1) sum += ans2;
	cout << sum << endl;
	return 0;
}


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

int main() {
  string s;
  long long  k;
  cin >> s >> k;
  long long ans = 0;
  long long size = s.size();

  if (size != 1){
  // 文字列の最初と最後が繋がってないやつ
  if (s.at(0) != s.at(size-1)){
    long long check = 0; // チェックするのが文字列sのどこか

    while(check < size-1){ // 最後までチェックしたら終了
      long long same = 1;
      for (long long i=check+1; i<size; i++){
        if (s.at(check) == s.at(i)){
          check++; same++;
        }
        else{
          check++; break;
        }
      }
      ans += same/2;
    }
    cout << ans * k <<endl;
  }

  /*
  // 文字列の最初から最後まで全部繋がってるやつ
  bool flagsuru=1;
  bool flagsimasu=1;
  while(flagsuru){
    for (int i=0; i<size-1; i++){
      if (s.at(i) != s.at(i+1)){
        flagsuru = 0;
        flagsimasu = 0;
        break;
      }
    }
  }

  if (flagsimasu) {
    int answer = size * k / 2;
    cout <<answer <<endl;
  }
  */

  // 文字列の最初と最後が繋がってるやつ
  else if (s.at(0) == s.at(size-1)){
    long long check = 0; // チェックするのが文字列sのどこか
    long long check2 = 0;
    long long check3 = size-1;
    long long same2 = 1;
    long long same3 = 1;
    long long same999 = 0;

    for (long long i=1; i<size; i++){
      if (s.at(check2) == s.at(i)){
        check2++; same2++;
      }
      else{
        check2++; break;
      }
    }
    for (long long i=size-2; i>=check2; i--){
      if (s.at(check3) == s.at(i)){
        check3--; same3++;
      }
      else{
        check3--; break;
      }
    }
    same999 = same2 + same3;
    // same2, same3：各々最初, 最後がどれだけ同じか
    // same999：最初と最後がどれだけ繋がってるか
    /* 0000000012312312312312312312300000000000
               ^                   ^
             check2              check3
       0000000000000000012000000000000000000000
                        ^^
                   check2check3
       0000000000000000001000000000000000000000
                         ^
                   check2, check3
    */

    check = check2; // 最初チェックした分は飛ばす
    while(check < check3){ // チェックした所までチェックしたら終了
      long long same = 1;
      for (long long i=check+1; i<check3+1; i++){
        if (s.at(check) == s.at(i)){
          check++; same++;
        }
        else{
          check++; break;
        }
      }
      ans += same/2;
    }
    /* ここまでで確認したこと
        1.文字列の最初, 最後がどれだけ繋がっているか
        2.文字列の中間のans
       やるべきこと
        1.最初、最後、最初＋最後を各々2で割り、各々1, 1, k-1を
          かけて答えに足す
        2.中間のansにkをかけて答えに足す
    */

    long long ans1 = same2 / 2 + same3 / 2 + same999 / 2 * (k-1);
    long long ans2 = ans * k;
    long long real_ans = ans1 + ans2;

    //cout << same2 / 2 <<" " << same3 / 2 <<" " <<same999 <<endl;
    //cout << ans1 <<endl;
    //cout << ans <<endl;
    cout << real_ans <<endl;
  }
  }
  else{
    cout << k/2 <<endl;
  }
}


#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include <bitset>
#include<math.h>
using namespace std;
#define INF 11000000000
#define MOD 1000000007
typedef long long ll;
typedef pair<ll,ll> P;

string s,s1;
string S;

int solve(){
    s=S;
    int count=0;
    for(int i=0;i<(int)s.size()-1;i++){
        if(s[i+1]==s[i]){
            count++;
            s[i+1]='?';
        }
    }
    return count;
}

int solve1(){
    s1=S;
    int count=0;
    for(int i=1;i<(int)s1.size()-1;i++){
        if(s1[i+1]==s1[i]){
            count++;
            s1[i+1]='?';
        }
    }
    return count;
}

int main(){
    ll K;
    cin>>S>>K;
    int num=(int)S.size();
    ll ans1=solve();
    ll ans=0;
    if(S[num-1]!=S[0]){
        ans=ans1*K; //〇
    }
    else if(S[num-1]==S[0] && S[0]!=S[1]){
        if(s[num-1]=='?') ans=ans1*K;
        else{
           ll ans2=solve1();
           if(s1[num-1]=='?'){
               if(K%2==0)  ans=(ans1+ans2+1)*(K/2);
               else ans=(ans1+ans2+1)*(K/2)+ans1;
           }else{
               if(K%2==0)  ans=(ans1+ans2+1)*(K/2);
               else ans=(ans1+ans2+1)*(K/2)+ans1;
           }
        }
    }
    else if(S[num-1]==S[0] && S[0]==S[1]){
       if(s[num-1]=='?') ans=(ans1)*K;
       else{
           ll ans2=solve1();
           if(s1[num-1]=='?'){
               if(K%2==0)  ans=(ans1+ans2+1)*(K/2);
               else ans=(ans1+ans2+1)*(K/2)+ans1;
           }else{ //miss
               if(K%2==0){ //misskokodake tasukete
                   ans=(ans1+ans2+1)*(K/2);
               }
               else{
                   ans=(ans1+ans2+1)*(K/2)+ans1;
               }
           }
       }
    }else ans=-1;
    if(ans==-1) return 1;
    cout<<ans<<endl;

}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(x) x.begin(),x.end()

int const N = 100001;
int k;
string s;
// a.b.a.aba.a
// aaba.a.a
// a.ba.a.aba.a.aba.a

int main(){
	cin >> s >> k;
	if(s.size() == 1){cout << k/2<<"\n";return 0;}
	char x = s[0];
	int count = 0;
	for(int i = 0; i<(int)s.size(); ++i)count += (s[i] == x ? 1: 0);
	if(count == (int)s.size()){return cout << (1ll * (count/2) * k), 0;}
	if(k <= 1){
	ll an = 0;
	for(int i = 0; i<(int)s.size()-1; ++i){
	   if(s[i] == s[i+1])s[i+1] = '.', ++an;
	}
	printf("%lld\n",an);
	return 0;
    }
    string o = s;
    char c = s[s.size()-1];
    int j = 0, cc = 0;
    while(j < (int)s.size()-1 && s[j] == c)++cc,s += c, ++j;
	int d = 0, rem = 0;
	for(int i = 0; i<(int)s.size()-1; ++i){
	   if(s[i] == s[i+1]){
		  s[i+1] = '.';
	      ++d;
	      if(i >= (int)o.size()-1)++rem;
	   }
	}
	ll an = (1ll * d * k);
	an -= cc;
	printf("%lld\n",an);
}


#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")

#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/rope>

using namespace std ;
using namespace  __gnu_pbds ;
using namespace __gnu_cxx ;

typedef long long ll ;
typedef long double ld ;

typedef pair<int, int> pii ;
typedef pair<ll,ll> pll ;

typedef vector<int> vi ;
typedef vector<ll> vll ;
typedef vector<pii> vpi ;
typedef vector<pll> vpl ;
typedef vector<vi> vvi ;

template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define rep(i,a,b) for (int i = (a); i <= (b); i++)
#define per(i,b,a) for (int i = (b); i >= (a); i--)

#define mp make_pair
#define eb emplace_back
#define pb push_back
#define fi first
#define se second

#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)

const int MOD1 = 1000000007 ;
const int MOD2 = 998244353 ;
const ll INFL = 1e18 ;
const int INFI = 2e9 ;
const int MAXN = 205 ;
const int LOGN = 22 ;
const int MAXM = (1 << LOGN) ;
const int ALPHA = 30 ;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()) ;

ll modpow(ll a, ll b, int MOD) {
    ll res = 1 ;
    while(b) {
        if(b&1) {
            res = res*a ;
            res %= MOD ;
        }
        a *= a ;
        a %= MOD ;
        b >>= 1 ;
    }
    return res%MOD ;
}
void upmin(int &a, int b) {
    if(a < b) {
        a = b ;
    }
}
void relax(int &a, int b) {
    if(a > b) {
        a = b ;
    }
}
ll add(ll a, ll b, int MOD) {
    a += b ;
    if(a >= MOD) {
        a -= MOD ;
    }
    return  a ;
}
ll subtract(ll a, ll b, int MOD) {
    a -= b ;
    if(a < 0) {
        a += MOD ;
    }
    return a ;
}
ll multiply(ll a, ll b, int MOD) {
    a *= b ;
    a %= MOD ;
    return a ;
}
string s ;
int n;
ll k ;
int dp[MAXN][ALPHA][ALPHA] ;
int main() {
    ios::sync_with_stdio(false) ;
    cin.tie(NULL) ;
    cin >> s >> k ;
    n = sz(s) ;
    rep(i,0,n-1) rep(j,0,25) rep(jj,0,25) dp[i][j][jj] = n + 15 ;
    rep(j,0,25) {
        int x = int(s[0] - 'a') ;
        int cost = 1 ;
        if(j == x) {
             cost = 0 ;
        }
        dp[0][j][j] = cost ;
    }
    rep(i,1,n-1) {
        rep(j,0,25) {
            rep(jj,0,25) {
               int cost = 1 ;
               if(j == int(s[i] - 'a')) {
                   cost = 0 ;
               }
               rep(jjj,0,25) {
                  if(j == jjj) continue ;
                  dp[i][j][jj] = min(dp[i-1][jjj][jj] + cost, dp[i][j][jj]) ;
               }
            }
        }
    }
    int best = n + 15 ;
    bool good ;
    rep(j,0,25) {
       rep(jj,0,25) {
          if(best > dp[n-1][j][jj]) {
              best = dp[n-1][j][jj] ;
              if(j == jj) {
                  good = false ;
              }
              else {
                  good = true ;
              }
          }
       }
    }
    ll res ;
    if(good) {
        res = k*best ;
        cout << res << endl ;
        return 0 ;
    }
    res = k*best + k - 1 ;
    int pbest = best ;
    best = n + 15 ;
    rep(j,0,25) {
        rep(jj,0,25) {
           if(j != jj) {
                best = min(best, dp[n-1][j][jj]) ;
           }
        }
    }
    res = min(res, (k-1)*best + pbest*1LL) ;
    cout << res << endl ;
    return 0 ;
}


#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string s;
	int k, len, t_a;
	long int t;

	t = 0;
	t_a = 0;
	len = 0;

	cin >> s;
	cin >> k;

	s += s;

	len = s.length();

	for (int i = 0; i < len; i++)
	{
		if (s[i] == s[i + 1])
		{
			t++;
			i++;
		}
	}

	if (t % 2)
	{
		if (t > 2)
		{
			cout << ((t - 1) / 2)*k + (k/2);
		}
		else {
			cout << (k - 1);
		}
	} else {
		cout << (t/2) * k;
	}

	return 0;
}


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

int main(){
  string S;
  int long long K;
  cin>>S>>K;
  int len = S.size();
  int x;
  int long long ans=0;
  if(len==1){
    cout<<K/2<<endl;
    exit(0);
  }
  if(len==2){
    if(S.at(0)==S.at(1)){
      cout<<K<<endl;
      exit(0);
    }
    else{
      cout<<0<<endl;
      exit(0);
    }
  }
  if(S.at(0)==S.at(len-1))
    x=1;
  else
    x=0;
  int num=0;
  if(x==0){
    for(int i=1;i<len;i++){
      if(S.at(i)==S.at(i-1))
        num++;
      else{
        ans+=((num+1)/2)*K;
        num=0;
      }
    }
    cout<<ans<<endl;
  }
  int rnum=0;
  int s=0;
  int e;
  if(x==1){
    for(int i=1;i<len-1;i++){
      if(S.at(i)==S.at(0))
        rnum++;
      else{
        s=i;
        break;
      }
    }
    if(rnum==len-2){
      ans=(len*K)/2;
      cout<<ans<<endl;
    }
    else{
      for(int i=len-2;i>0;i--){
        if(S.at(i)==S.at(len-1))
          rnum++;
        else{
          e=i;
          break;
        }
      }
      for(int i=s;i<e+2;i++){
        if(S.at(i)==S.at(i-1))
          num++;
        else{
          ans+=((num+1)/2)*K;
          num=0;
        }
      }
      rnum+=2;
      ans+=(rnum/2)*K;
      cout<<ans<<endl;
    }
  }
}


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

// iterator
#define REP(i,from, to) for(lli i=from;i<to;i++)
#define REPE(i,from, to) for(lli i=from;i<=to;i++)
#define REP_R(i,from, to) for(lli i=from;i>to;i--)
#define REPE_R(i,from, to) for(lli i=from;i>=to;i--)
#define REPIT(it,container) for(auto it = container.begin(); it != container.end(); it++)
#define REPIT_R(it,container) for(auto it = container.rbegin(); it != container.rend(); it++)

// input
#define cin1(x)             cin >> x
#define cin2(x, y)          cin >> x >> y
#define cin3(x, y, z)       cin >> x >> y >> z
#define ncin1(n, x)         REP(i, 0, n) {cin1(x[i]);}
#define ncin2(n, x, y)      REP(i, 0, n) {cin2(x[i], y[i]);}
#define ncin3(n, x, y, z)   REP(i, 0, n) {cin3(x[i], y[i], z[i]);}

// output
#define cout1(x)         cout << #x << ": " << x << endl;
#define cout2(x, y)      cout << #x << ": " << x << ", " << #y << ": " << y << endl;
#define cout3(x, y, z)   cout << #x << ": " << x << ", " << #y << ": " << y << ", " << #z << ": " << z << endl;;
#define ncout1(n, x)     REP(i, 0, n) {cout << #x << "[" << i << "]: "<< x[i] << endl;}

#define coutp(p)         cout << #p << ":" <<  " (" << p.first << ", " << p.second << ")" << endl;

// sort
#define sort_r(x, y)        sort(x, y, greater<lli>()); // 降順(5,4,3,,,)

#define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0]))

typedef long long int lli;
typedef pair<lli, lli> P;
typedef tuple<lli, lli, lli> tup;

int main() {
    string s;
    unsigned long long k;
    cin1(s);
    cin1(k);
    if (s.length() == 1) {
        if (k % 2 == 0)
            cout << k/2 << endl;
        else
            cout << (k-1)/2<<endl;
        return 0;
    }
    unsigned long long int ans = 0;
    unsigned long long int  con = 1;
    //cout1(s.length());
    REP(i,0,s.length()-1) {
        if (s[i] == s[i+1]) {
            con++;
        }
        else {
            if (con % 2 == 0) {
                //cout1(con/2);
                ans += con /2 ;
            }
            else if (con != 1) {
                //cout1((con-1)/2);
                ans += (con - 1)/2;
            }
            con = 1;
        }
    }
    if (con != 1) {
        if (con % 2 == 0) {
            //cout1(con/2);
            ans += con /2 ;
        }
        else if (con != 1) {
            //cout1((con-1)/2);
            ans += (con - 1)/2;
        }
    }
    unsigned long long first_count = 1;
    unsigned long long second_count = 1;
    REP(i,0,s.length()-1) {
        if (s[i] != s[i+1])
            break;
        first_count++;
    }
    REP_R(i,s.length()-1,0) {
        if (s[i] != s[i-1])
            break;
        second_count++;
    }

    if (first_count == second_count && first_count == s.length()) {
        if (first_count % 2 == 0) {
            cout << ans * k << endl;
        }
        else {
            cout << ans * k + k/2 << endl;
        }
        return 0;
    }

    unsigned long long x = 0;
    unsigned long long y = 0;
    unsigned long long z = 0;
    if (first_count != 1 && second_count != 1) {

        if (first_count != 1) {
            ans -= first_count / 2;
        }
        if (second_count != 1) {
            ans -= second_count / 2;
        }
        //cout1(first_count);
        //cout1(second_count);

        x = first_count / 2;
        z = second_count / 2;

        y = (first_count + second_count) * (k-1) / 2;

    }

    //if (first_count == second_count && first_count == s.length()) {
    //    if (k % 2 == 0)
    //        x = k/2;
    //    else
    //        x = (k-1)/2;
    //}
    //else if ((s[0] == s[s.length()-1] && first_count == 1 && second_count == 1) ||
    //    (s[0] == s[s.length()-1] && first_count == 1 && second_count % 2 == 1) ||
    //    (s[0] == s[s.length()-1] && first_count % 2 == 1 && second_count == 1) )
    //    x = (k-1);
    //else if (s[0] == s[s.length()-1] && (first_count % 2 == 1 && second_count % 2 == 1)) {
    //    if (k % 2 == 0)
    //        x = k/2;
    //    else
    //        x = (k+1)/2;
    //}
    cout << ans * k + x + y + z << endl;
}


#pragma GCC optimize ("O3")
#include <bits/stdc++.h>
#define DEBUG true
#ifdef ONLINE_JUDGE
#undef DEBUG
#define DEBUG false
#endif

using namespace std;

#define MAXN ((ll)2e5+5)
#define MOD ((ll)1e9 + 7)
#define INF ((ll)1e9 + 9)
#define ll long long
#define _ << " " <<
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define TRACE(x) if(DEBUG) cerr << #x << " = " << x << endl;
#define TRACE2(x,y) if(DEBUG) cerr << #x << " = " << x << " | " << #y << " = " << y << endl;
#define pb push_back
#define all(x) x.begin(), x.end()
#define endl "\n"
#define pii pair<ll,ll>
#define mid ((l+r)/2)

string s;
ll k,n;
ll ans;

map <int,int> mp;

ll f(string a)
{
	ll ct = 0 ;
	ll n_ = a.size();
	for (ll i = 1; i < n_; ++i)
	{
		if(a[i] == a[i-1])
		{
			a[i] = '#';
			ct++;
		}
	}
	return ct;
}

int main()
{
	ios_base::sync_with_stdio(false);cin.tie(0);
	cin >> s >> k;
	n = s.size();

	for (int i = 0; i < n; ++i)
		mp[s[i]]++;

	if(mp.size() == 1)
		ans = (k * n) / 2;
	else
	{
		ll l = 0, r = 0;
		while(s[l] == s[l+1]) l++;
		while(s[n-1-r] == s[n-2-r]) r++;

		l++;
		r++;

		TRACE2(l,r);

		ans = l / 2 + r / 2;

		if(s[0] == s[n-1])
			ans += (k-1) * ((l+r)/2);
		else
			ans += (k-1) * (l/2 + r/2);

		string tmp;
		for (int i = l; i < n-r; ++i)
			tmp += s[i];

		TRACE2(tmp,f(tmp));

		ans += f(tmp) * k;
	}

	cout << fixed << ans << endl;
}


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

int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s;
cin >> s;
long long int k;
cin >> k;
long long int count = 0;
if (s[s.length()-1] == s[0]){
s += s[0];
}
for (int j = 1; j < s.length(); ++j){
if (s[j-1] == s[j]){
        ++count;
        if (j == s.length()-2){
break;
        }else{
++j;
        }
}
}

long long int a = count * k;
cout << a << "\n";
return 0;
}


#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <functional>
#include <limits>
#include <numeric>
#include <string>
#include <tuple>
#include <utility>
#include <array>
#include <vector>
#include <deque>
#include <forward_list>
#include <list>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>

using namespace std;

#define popcount __builtin_popcountll
#define FORS(i, s, n) for (int i = (s); i < (n); ++i)
#define RFORS(i, s, n) for (int i = (n)-1; i >= (s); --i)
#define FOR(i, n) FORS(i, 0, n)
#define RFOR(i, n) RFORS(i, 0, n)
#define FI(n) FOR(i, n)
#define RFI(n) RFOR(i, n)
#define ALL(x) (x).begin(), (x).end()
#define RALL(x) (x).rbegin(), (x).rend()
#define MP(x,y) make_pair((x),(y))
#define PB(x) push_back((x))
#define SZ(c) int((c).size())
#define FOR_SETTED_BIT(bit, mask) for (int bit = 0; (mask) >> bit; ++bit) if (1&(mask >> bit))
#define FOR_NONZERO_SUBMASK(submask, mask) for (int submask=(mask); submask; submask=(submask-1)&(mask))
#define PI (3.141592653589793L)
#define MODULO ((ll)1e9+7LL)

typedef long long ll;
typedef long double ld;
typedef pair < int, int > pi;
typedef pair < ll, ll > pll;
typedef pair < ld, ld > pld;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ld> vld;
typedef vector<pi> vpi;
typedef vector<pll> vpll;
typedef vector<pld> vpld;
typedef list<int> li;
typedef list<ll> lll;
typedef list<ld> lld;
typedef list<pi> lpi;
typedef list<pll> lpll;
typedef list<pld> lpld;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vld> vvld;
typedef vector<vpi> vvpi;
typedef vector<vpll> vvpll;
typedef vector<vpld> vvpld;
typedef vector<li> vli;
typedef vector<lll> vlll;
typedef vector<lld> vlld;
typedef vector<lpi> vlpi;
typedef vector<lpll> vlpll;
typedef vector<lpld> vlpld;
typedef set<int> si;
typedef set<ll> sll;
typedef set<pi> spi;
typedef set<pll> spll;
typedef vector< list < pair < int, ll > > > AdjacencyLists;
typedef vvll AdjacencyMatrix;

template<class T> inline T sqr(const T &x) { return x * x; }
inline ll sqr(int x){return sqr<ll>(x);}
template<class T>T binpow(const T &a, ll n) { return n == 0 ? 1 : sqr(binpow(a, n / 2))* (n % 2 ? a : 1); }
ll binpow(ll a, ll n, ll modulo) { return n == 0 ? 1 : sqr(binpow(a, n / 2, modulo)) % modulo * (n % 2 ? a : 1) % modulo; }

ll gcd(ll a, ll b, ll &x, ll &y)
{
    if (a == 0)
    {
        x = 0;
        y = 1;
        return b;
    }
    ll x1, y1;
    ll d = gcd(b%a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return d;
}
inline ll phi (ll n) {
    ll result = n;
    for (ll i=2; i*i<=n; ++i)
        if (n % i == 0) {
            while (n % i == 0)
                n /= i;
            result -= result / i;
        }
    if (n > 1)
        result -= result / n;
    return result;
}
inline vll inverseAll(ll m)
{
    vll r(m);
    r[1] = 1;
    for (int i=2; i<m; ++i)
        r[i] = (m - (m/i) * r[m%i] % m) % m;
    return r;
}
inline ll gcd(ll a, ll b) { return gcd(a, b, a, b); }
inline ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
inline ll llrand()
{
    const ll lsbToFill = (sizeof(ll) << 3) - 1;
    const ll bitsFilledInIteration = popcount(RAND_MAX);
    ll number = 0;

    for (ll lsbFilled = 0; lsbFilled <= lsbToFill; lsbFilled += bitsFilledInIteration)
    {
        number ^= (((ll)rand()) << lsbFilled);
    }

    return number & numeric_limits<ll>::max();
}
inline ll llrand(ll begin, ll end)
{
    return begin + llrand() % (end - begin);
}

struct Dinic {
    struct Edge {
        int u, v;
        ll cap, flow;
        Edge() {}
        Edge(int u, int v, ll cap): u(u), v(v), cap(cap), flow(0) {}
    };

    int N;
    vector<Edge> E;
    vector<vector<int>> g;
    vector<int> d, pt;

    Dinic(int N): N(N), E(0), g(N), d(N), pt(N) {}

    void AddEdge(int u, int v, ll cap) {
        if (u != v) {
            E.emplace_back(Edge(u, v, cap));
            g[u].emplace_back(E.size() - 1);
            E.emplace_back(Edge(v, u, 0));
            g[v].emplace_back(E.size() - 1);
        }
    }

    bool BFS(int S, int T) {
        queue<int> q({S});
        fill(d.begin(), d.end(), N + 1);
        d[S] = 0;
        while(!q.empty()) {
            int u = q.front(); q.pop();
            if (u == T) break;
            for (int k: g[u]) {
                Edge &e = E[k];
                if (e.flow < e.cap && d[e.v] > d[e.u] + 1) {
                    d[e.v] = d[e.u] + 1;
                    q.emplace(e.v);
                }
            }
        }
        return d[T] != N + 1;
    }

    ll DFS(int u, int T, ll flow = -1) {
        if (u == T || flow == 0) return flow;
        for (int &i = pt[u]; i < g[u].size(); ++i) {
            Edge &e = E[g[u][i]];
            Edge &oe = E[g[u][i]^1];
            if (d[e.v] == d[e.u] + 1) {
                ll amt = e.cap - e.flow;
                if (flow != -1 && amt > flow) amt = flow;
                if (ll pushed = DFS(e.v, T, amt)) {
                    e.flow += pushed;
                    oe.flow -= pushed;
                    return pushed;
                }
            }
        }
        return 0;
    }

    ll MaxFlow(int S, int T) {
        ll total = 0;
        while (BFS(S, T)) {
            fill(pt.begin(), pt.end(), 0);
            while (ll flow = DFS(S, T))
                total += flow;
        }
        return total;
    }
};

vll Dijkstra(const AdjacencyLists &g, int s)
{
    vll d(SZ(g), numeric_limits<ll>::max() / 2LL);
    priority_queue < pair<ll, int> > q;

    d[s] = 0;
    q.emplace(-0, s);

    while (!q.empty())
    {
        while (q.top().first > d[q.top().second]) { q.pop(); }
        int v = q.top().second;

        q.pop();

        for (const auto &cw : g[v])
        {
            if (d[v] + cw.second < d[cw.first])
            {
                d[cw.first] = d[v] + cw.second;
                q.emplace(-d[cw.first], cw.first);
            }
        }
    }

    return d;
}

struct BinarySearchIterator : public std::iterator<std::forward_iterator_tag, bool>
{
    ll value;

    typename iterator_traits<BinarySearchIterator>::difference_type operator - (const BinarySearchIterator &it) const { return value - it.value; }

    BinarySearchIterator& operator ++() { ++value; return *this; }

    bool operator != (const BinarySearchIterator &it) const { return value != it.value; }

    bool operator*() const { /*insert code here*/ return true; }
};

template < int ALPHA >
class AhoCorasick
{
public:
    static const int ILLEGAL_INDEX;
    static const int ROOT;

    struct Node
    {
        bool leaf;
        int parent;
        int parentCharacter;
        int link;

        int next[ALPHA];
        int go[ALPHA];
        int outputFunction;

        Node(int parent = ILLEGAL_INDEX, int parentCharacter = ALPHA) :
            leaf(false),
            parent(parent),
            parentCharacter(parentCharacter),
            link(ILLEGAL_INDEX),
            outputFunction(ILLEGAL_INDEX)
        {
            fill_n(next, ALPHA, ILLEGAL_INDEX);
            fill_n(go, ALPHA, ILLEGAL_INDEX);
        }
    };

    vector<Node> tree = vector<Node>(1);

    AhoCorasick(){}
    AhoCorasick(int maxStatesNumber)
    {
        tree.reserve(maxStatesNumber);
    }

    template < class Iterator >
    void add(int length, const Iterator begin)
    {
        int vertex = ROOT;

        for (int i = 0; i < length; ++i)
        {
            if (ILLEGAL_INDEX == tree[vertex].next[begin[i]])
            {
                tree[vertex].next[begin[i]] = SZ(tree);
                tree.push_back(Node(vertex, begin[i]));
            }

            vertex = tree[vertex].next[begin[i]];
        }

        tree[vertex].leaf = true;
    }

    int getLink(int vertex)
    {
        assert(0 <= vertex && vertex < tree.size());

        if (ILLEGAL_INDEX == tree[vertex].link)
        {
            if (ROOT == vertex || ROOT == tree[vertex].parent)
            {
                tree[vertex].link = ROOT;
            }
            else
            {
                tree[vertex].link = go(getLink(tree[vertex].parent), tree[vertex].parentCharacter);
            }
        }

        return tree[vertex].link;
    }

    int go(int vertex, int character)
    {
        assert(0 <= character && character < ALPHA);
        assert(0 <= vertex && vertex < tree.size());

        if (ILLEGAL_INDEX == tree[vertex].go[character])
        {
            if (ILLEGAL_INDEX == tree[vertex].next[character])
            {
                tree[vertex].go[character] = ROOT == vertex ? ROOT : go(getLink(vertex), character);
            }
            else
            {
                tree[vertex].go[character] = tree[vertex].next[character];
            }
        }

        return tree[vertex].go[character];
    }

    int getOutputFunction(int vertex)
    {
        assert(0 <= vertex && vertex < tree.size());

        if (ILLEGAL_INDEX == tree[vertex].outputFunction)
        {
            if (tree[vertex].leaf || ROOT == vertex)
            {
                tree[vertex].outputFunction = vertex;
            }
            else
            {
                tree[vertex].outputFunction = getOutputFunction(getLink(vertex));
            }
        }

        return tree[vertex].outputFunction;
    }
};

template < int ALPHA > const int AhoCorasick<ALPHA>::ILLEGAL_INDEX = -1;
template < int ALPHA > const int AhoCorasick<ALPHA>::ROOT = 0;

struct UnionFind {
    vi parent;
    vi rank;
    UnionFind(int n) : parent(n), rank(n) {
        for (int i = 0; i < n; ++i) {
            parent[i] = i;
            rank[i] = 0;
        }
    }
    int find_set (int v) {
        if (v == parent[v])
            return v;
        return parent[v] = find_set (parent[v]);
    }
    void union_sets (int a, int b) {
        a = find_set (a);
        b = find_set (b);
        if (a != b) {
            if (rank[a] < rank[b])
                swap (a, b);
            parent[b] = a;
            if (rank[a] == rank[b])
                ++rank[a];
        }
    }
};

vi solve(const string &s) {
    int begin = 0;
    vi change(SZ(s), false);

    FI(SZ(s) + 1) {
        if (i == SZ(s) || s[begin] != s[i]) {
            begin = i;
        }

        if (i < SZ(s) && (i - begin) % 2 == 1) {
            change[i] = true;
        }
    }

    return change;
}

ll solve(const string &s, ll k) {
    if (1 == k) {
        auto one = solve(s);
        return accumulate(ALL(one), 0LL);
    }

    auto three = solve(s + s + s);

    ll left_ = accumulate(three.begin(), three.begin() + SZ(s), 0LL);
    ll middle_ = accumulate(three.begin() + SZ(s), three.begin() + 2 * SZ(s), 0LL);
    ll right_ = accumulate(three.begin() + 2 * SZ(s), three.begin() + 3 * SZ(s), 0LL);

    return left_ + (k - 2LL) * middle_ + right_;
}

int main(int argc, const char * argv[]) {
#ifdef DEBUG
    assert(4 == solve("issii", 2));
    assert(81 == solve("qq", 81));
#endif
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.precision(13);
    cout.setf(ios::fixed);
    srand((unsigned int)time(NULL));

    string s;
    ll k;

    while (cin >> s >> k) {
        cout << solve(s, k) << endl;
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define modulo 1000000007
#define mod(mod_x) ((((long long)mod_x+modulo))%modulo)
#define Inf 10000000000000000

int main(){

	string S;
	cin>>S;

	set<char> s;
	for(int i=0;i<S.size();i++){
		s.insert(S[i]);
	}

	long long K;
	cin>>K;

	long long ans = 0;

	if(s.size()!=1){
		for(int i=1;i<S.size();i++){
			if(S[i]==S[i-1]){
				ans++;
				S[i]='(';
			}
		}

		ans *= K;

		if(S[0]==S[S.size()-1]){
			ans += K-1;
		}
	}
	else{
		ans = (K*S.size())/2;
	}

	cout<<ans<<endl;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); i++)
typedef long long ll;

int main()
{
    ll n, m;
    cin >> n >> m;
    vector<ll> A(n);
    rep(i, n) { cin >> A.at(i); }
    while (m--) {
        sort(A.begin(), A.end());
        A.back() /= 2;
    }
    cout << accumulate(A.begin(), A.end(), 0LL) << endl;
}

Score : 400 points

Problem Statement

Takahashi is going to buy N items one by one.

The price of the i-th item he buys is A_i yen (the currency of Japan).

He has M discount tickets, and he can use any number of them when buying an item.

If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for 9 yen, as follows:

Buy the 1-st item for 2 yen without tickets.

Buy the 2-nd item for 3 yen with 2 tickets.

Buy the 3-rd item for 4 yen with 1 ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced 1000000000 yen for 0 yen with 100000 tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000


#include<cstdio>
#include<stdio.h>
#include<math.h>
#include<queue>
#include<iostream>
#include<string>
using namespace std;
int main()
{
	priority_queue<long long>q;
	int m,n,op;
	long long sum=0;
	cin>>n>>m;
	for(int i=0;i<n;i++)
    {
		cin>>op;
		q.push(op);
	}
	while(m--)
	{
		op=q.top()/2;
		q.pop();
		q.push(op);
	}
	while(!q.empty())
	{
		sum+=q.top();
		q.pop();
	}
	cout<<sum<<endl;
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <string>
#include <cctype>
#include <map>
#include <queue>

using namespace std;

const int mod = 1000000007;
#define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0]))
#define ll long long

int main()
{
    int n,m;
    cin >> n >> m;

    priority_queue<ll> que;
    for (int i = 0; i < n; i++)
    {
        ll priceNum;
        cin >> priceNum;

        que.push(priceNum);
    }

    for (int i = 0; i < m; i++)
    {
        ll price = que.top();
        price /= 2;
        que.pop();
        que.push(price);
    }

    ll sum = 0;
    for (int i = 0; i < n; i++)
    {
        sum += que.top();
        que.pop();
    }

    cout << sum << endl;
}


#include <iostream>
#include <string>
#include <algorithm>
#include <utility>
using namespace std;

int main(){
    int n,m;
    cin >> n >> m;
    int a[n];

    for(int i = 0;i<n;i++){
        cin >> a[i];
    }
    sort(a,a+n);
    int lowest = 0;
    int highest = n-1;
    for(int i = 0;i < m;i++){
        a[n-1] /= 2;
        while(true){
            int b = (highest + lowest)/2;
            if(highest - lowest == 0){
                swap(a[n-1],a[lowest]);
              	//for(int j = 0;j<n;j++)cout << a[j] << endl;
                break;

            }
            if(a[n-1] > a[b]){
                lowest = b+1;
            }else{
                highest = b;
            }
          //cout << a[b] << endl;
        }
    }
    unsigned long long sum = 0;
    for(int i = 0;i < n;i++){
        sum += a[i];
    }
    cout << sum << endl;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <utility>
#include <iomanip>
#include <queue>
using namespace std;
typedef long long ll;

const ll MOD = 1e9+7;
priority_queue<ll> que;
int main()
{
	int n,m;
	ll ans=0;
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		ll a;
		cin>>a;
		que.push(a);
	}
	for(int i=0;i<m;i++)
	{
		ll b=que.top();que.pop();
		b/=2;
		que.push(b);
	}
	while(!que.empty())
	{
		ans+=que.top();que.pop();
	}
	cout<<ans<<endl;
	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#define MOD 1000000007
#define INF 100000000
//#define MOD 3025908521
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <bitset>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <string>
#include <functional>
#include <algorithm>
#include <iterator>
#include <cstdio>
#include <utility>
#include <unordered_map>
#include <cmath>
#include <chrono>
#include <random>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

typedef pair<ll, ll> P;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vector<int>> vvi;
typedef vector<vector<ll>> vvl;
#define FOR(i,a,b) for(ll i=(a);i<=(b);++i)
#define RFOR(i,a,b) for(ll i=(a);i>=(b);i--)
#define REP(i,n) FOR(i,0,n-1)
#define RREP(i,n) RFOR(i,n-1,0)
#define ALL(obj) (obj).begin(), (obj).end()

inline ll madd(ll a, ll b) {
	a %= MOD;b %= MOD;
	return (a + b) % MOD;
}
inline ll msub(ll a, ll b) {
	a %= MOD;b %= MOD;
	a += MOD;
	return (a - b) % MOD;
}
inline ll mmul(ll a, ll b) {
	a %= MOD;b %= MOD;
	return (a*b) % MOD;
}
inline ll mpow(ll a, ll r) {
	long long res = 1;
	while (r > 0) {
		if (r & 1) res = res * a % MOD;
		a = a * a % MOD;
		r >>= 1;
	}
	return res;
}
inline ll minv(ll a) {
	a %= MOD;
	ll b = MOD, u = 0, v = 1;
	while (a) {
		ll t = b / a;
		b -= t * a; swap(a, b);
		u -= t * v; swap(u, v);
	}
	if (u < 0) u += MOD;
	return u;
}
inline ll mdiv(ll a, ll b) {
	a %= MOD;
	a *= minv(b);
	return a%MOD;
}

//ll fact[]
//inline ll combi(int a, int b) {
//	return mmul(fact[a], mmul(fact_inv[b], fact_inv[a - b]));
//}

struct UnionFind {
	vector<int> data;
	UnionFind(int size) : data(size, -1) { }
	bool unite(int x, int y) {
		x = root(x); y = root(y);
		if (x != y) {
			if (data[y] < data[x]) swap(x, y);
			data[x] += data[y]; data[y] = x;
		}
		return x != y;
	}
	bool same(int x, int y) {
		return root(x) == root(y);
	}
	int root(int x) {
		return data[x] < 0 ? x : data[x] = root(data[x]);
	}
	int size(int x) {
		return -data[root(x)];
	}
};

struct edge { ll to, cost; };

int main() {
	multiset<ll> st;
	ll n, m;
	cin >> n >> m;
	REP(i, n) {
		ll j;
		cin >> j;
		st.insert(j);
	}
	REP(i, m) {
		auto itr = st.end();
		itr--;
		ll top = *itr/2;
		st.erase(itr);
		st.insert(top);
	}
	ll result = 0;
	auto itr = st.begin();
	REP(i, n) {
		result += *itr;
		itr++;
	}
	cout << result;

	return 0;
}


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

typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;

template<class T>
inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}

const ll INF = 1e18;
const ll MOD = 998244353;
const ll MX = 1000001;

int N, ans;
string S;
int cnt[26];
vector<int> ocs[26];

void solve() {
    cin >> N >> S;

    for (int i = 0; i < N; i++) {
		ocs[S[i] - 97].push_back(i);
	}
	for (int i = 0; i < N; i++) {
		int dec = S[i] - 97;
		// cout << dec << "\n";
		// cout << ocs[dec].size() << "\n";
		for (int oc = cnt[dec] + 1; oc < ocs[dec].size(); oc++) {
			int len = 0;
			int a = i, b = ocs[dec][oc];
			// cout << a << " " << b << "\n";
			while (a < ocs[dec][oc] && b < N && S[a] == S[b]) {
				len++;
				a++; b++;
			}

			chmax(ans, len);
		}
		cnt[dec]++;
	}
	cout << ans;
}

int main() {
	cin.sync_with_stdio(0); cin.tie(0);
    ll T = 1; // cin >> T;
    while (T--) solve();
    return 0;
    // You should actually read the stuff at the bottom
}

/* Stuff to Look For
 * -----------------
 * Int overflow, array bounds
 * Initializing all variables, avoid weird behavior
 * Edge cases(n = 0, n = 1)
 * Just return 0 after result
 */

Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

2 \leq N \leq 5 \times 10^3

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5


#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <assert.h>
#include <deque>
using namespace std;

typedef unsigned long long UL;
typedef long long LL;
#define LP(i, a, b) for (int i = int(a); i < int(b); i++)
#define LPE(i, a, b) for (int i = int(a); i <= int(b); i++)
typedef pair<int, int> PII;
typedef vector<vector<PII> > WAL;
typedef vector<vector<int> > SAL;
#define Ep 1e-13

#define INF 1e9
const int MaxSize = 1050 + 10;
//const LL MOD = 1e9 + 7;
const LL MOD = 99999;
const int AS = 26;

string s;

/*
 https://atcoder.jp/contests/abc142/tasks/abc142_e
 E - Get Everything
 */
int N;

LL const BASE = 256;

//don't forget to lower case if you are doing string matching
LL sHash(string s) {
	LL h = 0;
	LP(i, 0, s.size())
	{
		h = (h * BASE) + (LL) s[i] - 'a'; //very similar idea to base number calculation
		h %= MOD;
	}

	return h;
}

bool good(int winL) {

	LL hash = 0;
	LL topBase = 1;
	SAL list(MOD);
	LP(i, 0, winL)
	{
		if (i > 0) {
			topBase *= BASE;
			topBase %= MOD;
		}

		hash *= BASE;
		hash %= MOD;
		hash += (LL) (s[i] - 'a');
		hash %= MOD;
	}
	list.at(hash).push_back(0);

	LP(i, winL, N)
	{
		//slide the hash
		hash -= topBase * (LL) (s[i - winL] - 'a');
		hash %= MOD; //watch out for the negative case!
		hash += MOD;
		hash %= MOD;

		hash *= BASE;
		hash %= MOD;
		hash += (LL) (s[i] - 'a');
		hash %= MOD;
		list.at(hash).push_back(i - winL + 1);
	}

	LP(slot, 0, MOD)
	{
		int ls = list.at(slot).size();
		if (ls < 2)
			continue;

		LP(i, 0, ls)
		{
			LP(j, i+1, ls)
			{
				int asi = list.at(slot)[i];
				int bsi = list.at(slot)[j];
				//cout << asi << " " << bsi << " " << winL << endl;
				if ((bsi - asi) < winL)
					continue;

				bool match = true;
				LP (k, 0, winL)
				{
					if (s[asi + k] != s[bsi + k]) {
						match = false;
						break;
					}
				}

				if (match) {
					return true;
				}
			}
		}
	}

	return false;
}

int main() {

	ios_base::sync_with_stdio(false);
	//freopen("/Users/georgeli/pycp/A_1.in", "r", stdin);
	cin >> N >> s;
	//check 1 case

	int low = 0;
	int high = N;

	while (low < high) {
		int mid = (low + high) / 2;
		if (good(mid)) {
			if (mid == low) {
				if (good(mid + 1)) {
					low = mid + 1;
				} else {
					low = mid;
				}
				break;
			} else {
				low = mid;
			}
		} else {
			high = mid - 1;
		}
	}

	cout << low;

	return 0;
}


// ~maqsat~
/*
**    “Anyone who has never made a mistake has never tried anything new.”
**    © Albert Einstein
*/

// #pragma GCC target ("avx2")
// #pragma GCC optimization ("Ofast")
// #pragma GCC optimization ("unroll-loops")

// #pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>

#define F first
#define S second
#define in insert
#define pb push_back
#define eb emplace_back
#define sz(x) int(x.size())
#define all(x) x.begin(), x.end()
#define count1 __builtin_popcountl
#define debug(x) cerr << (#x) << " = " << (x) << "\n"
#define ACCELERATE ios_base::sync_with_stdio(false),cin.tie(nullptr)
#define fre(f) if(fopen(f".in", "r")) freopen(f".in", "r", stdin),freopen(f".out", "w", stdout)

using namespace std;
using namespace __gnu_pbds;

using ll = long long;
using ull = unsigned long long;
// using big = __int128_t; // -10^38...10^38
using db = double;
using ld = long double;
typedef pair<int,int> ii;
typedef pair<ll,ll> pll;

template <class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class T> inline void cmin(T &a, T b) { a = min(a, b); }
template <class T> inline void cmax(T &a, T b) { a = max(a, b); }

const int oo = 0x3f3f3f3f;
const ll N = 1e5 + 345;
const ll MOD = 1e9 + 7;
const ll INF = 1e10 + 9;
const db EPS = 1e-9;
const db PI = acos(-1); // 3.14159265358979323846
const int dx[] = {1, -1, 0, 0, 1, 1, -1, -1};
const int dy[] = {0, 0, 1, -1, 1, -1, -1, 1};

int dp[5010][5010];
int main() {
    fre("");
    ACCELERATE;

	int n;
	cin >> n;

	string s;
	cin >> s;

	int ans = 0;
	for(int i = 1; i <= n; i++) {
		for(int j = i + 1; j <= n; j++) {
			if(s[i-1] == s[j-1] && j - i > dp[i-1][j-1]) {
				dp[i][j] = dp[i-1][j-1] + 1;
				cmax(ans, dp[i][j]);
			}
		}
	}

	cout << ans;
    return 0;
}
/*

*/


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const ll P = 43;
const ll MOD = 1e9+7;

int main(){

    int n;
    string s;
    cin >> n >> s;
    vector<ll> pw(n+1);
    pw[0] = 1;
    for(int i = 1; i <= n; i++)
        pw[i] = (pw[i-1]*P)%MOD;
    map<int, int> mp;
    int ans = 0;
    for(int i = 0; i < n; i++){
        ll hash = 0;
        for(int j = i, len = 1; j < n; j++, len++){
            hash = ( hash + (s[j]-'a'+1)*pw[len-1] )%MOD;
            if(mp.find(hash) != mp.end()){
                if(mp[hash]+len <= j)
                    ans = max(ans, len);
            }else{
                mp[hash] = j;
            }
        }
    }

    cout << ans << endl;
    return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
#define all(v) v.begin(),v.end()

using namespace std;
typedef long long ll;

int main()
{
    int N;
    cin >> N;
    string S;
    cin >> S;
    int ans = 0;

    for (int i = 1; i < N; i++) {
        for (int j = 0; j < N-i; j++) {

            if(S[i] == S[j]){
                int a = 1;

                while (j+a<=i && i <= N-a+1) {
                    if(S[i+a-1] == S[j+a-1]) a++;
                    else break;
                }
                //i += a-1;
                j += a-1;
                //cout << a << endl;
                /*
                for (int h = i; h < i+a; h++) {
                    cout << S[h] << " " << h << " ";
                }
                cout << endl;
                for (int h = j; h < j+a; h++) {
                    cout << S[h] << " " << h << " ";
                }
                cout << endl;
                cout << endl;
                 */
                ans = max(a-1, ans);
            }

        }
    }

    cout << ans << endl;

    return 0;
}


//PDF解説に倣ってZ-algorithm
#include<bits/stdc++.h>
using namespace std;

int main(){
  int n;
  string s;
  cin>> n >> s;

  int ans=0;
  for (int i=0; i<n; i++){
    vector<int> v(n);
    v[i]=n-i;
    int j=i+1,k=0;
    while (j<n){
      while (j+k<n && s[i+k]==s[j+k]) k++;
      v[j]=k;
      if (k==0){
        j++;
        continue;
      }
      int l=1;
      while (l+v[i+l]<k){
        v[j+l]=v[i+l];
        l++;
      }
      j+=l; k-=l;
    }
    for (int j=i+1; j<n-ans; j++){
      if (v[j]<=j-i) ans=max(ans,v[j]);
    }
  }

  cout<< ans <<endl;
}


#define _CRT_SECURE_NO_WARNING
//#include <bits/stdc++.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <queue>

// #include <stack>
// #include <queue>
// #include <set>
// #include <tuple>
// #include <list>
// #include <numeric>
// #include <random>
// #include <regex>
// #include <utility>

using namespace std;
const int INF = (int)1e9;

//#define DEBUG

void solution() {
	int n, m, q;
	cin >> n;
	string s;
	cin >> s;
	int len = n / 2;
	while (len > 0) {
		for (int i = 0; i < n - len * 2; ++i) {
			for (int j = i + len; j < n - len + 1; ++j) {
				if (s.compare(i, len, s, j, len) == 0) {
					goto answ;
				}
			}
		}
		len--;
	}
	answ: cout << len;
}

int main() {
  // freopen("input.txt", "r", stdin);
  // freopen("output.txt", "w", stdout);
	solution();
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define For(i,n,k) for(ll i=(n);i<(k);i++)
int main(){
    ll n,ik,ans=0;
    string s;
    cin>>n>>s;
    //s="";For(i,0,20) s+="qwertyuiopasdfghjklzxcvbnm";n=s.size();
    if(n!=5000){
        For(i,0,10) s+='*';
        For(i,1,1+n/2){
            map<string,ll> bubun;
            string k=s.substr(0,i);
            bubun[k]=i;
            For(j,i,n){
                k.erase(0,1);
                k+=s.at(j);
                ik=bubun[k];
                if(ik==0){
                    bubun[k]=j+1;
                }
                else if(ik+i<=j+1){
                    ans=i;
                    break;
                }
            }
            if(ans!=i){
                break;
            }
        }
        cout<<ans<<endl;
    }
    else{
        For(l,0,10) s+='*';
        ll kouho=n/4;
        For(num,0,8){
            bool flag=false;
            map<string,ll> bubun;
            string k=s.substr(0,kouho);
            bubun[k]=kouho;
            For(j,kouho,n){
                k.erase(0,1);
                k+=s.at(j);
                ik=bubun[k];
                if(ik==0){
                    bubun[k]=j+1;
                }
                else if(ik+kouho<=j+1){
                    flag=true;
                    break;
                }
            }
            ll div=pow(2,num+2);
            if(flag) kouho+=n/div;
            else kouho-=n/div;
        }
        ans=kouho;
        For(i,ans,1+n/2){
            bool flag=false;
            map<string,ll> bubun;
            string k=s.substr(0,i);
            bubun[k]=i;
            For(j,i,n){
                k.erase(0,1);
                k+=s.at(j);
                ik=bubun[k];
                if(ik==0){
                    bubun[k]=j+1;
                }
                else if(ik+i<=j+1){
                flag=true;
                    break;
                }
            }
            if(flag){
                ans=i;
                continue;
            }
            else{
                break;
            }
        }
        cout<<ans<<endl;
    }
}


#include <cstdio>
#include <cstring>
#include <algorithm>
#include <bits/stdc++.h>

using namespace std;
const int maxn=2e4+10;
const int N=0x3f3f3f3f;

int ary[maxn],rnk[maxn],hgt[maxn],t1[maxn],t2[maxn],sum[maxn],sa[maxn];

void getsa(int *r,int *sa,int n,int m)
{
    int *x,*y,*t;
    int i,j,p;
    x=t1,y=t2;
    for(i=0;i<m;i++) sum[i]=0;
    for(i=0;i<n;i++) sum[x[i]=r[i]]++;
    for(i=1;i<m;i++) sum[i]+=sum[i-1];
    for(i=n-1;i>=0;i--) sa[--sum[x[i]]]=i;
    for(p=1,j=1;p<n;j*=2)
    {
        for(p=0,i=n-j;i<n;i++) y[p++]=i;
        for(i=0;i<n;i++) if(sa[i]>=j) y[p++]=sa[i]-j;
        for(i=0;i<m;i++) sum[i]=0;
        for(i=0;i<n;i++) sum[x[y[i]]]++;
        for(i=1;i<m;i++) sum[i]+=sum[i-1];
        for(i=n-1;i>=0;i--) sa[--sum[x[y[i]]]]=y[i];
        t=x,x=y,y=t;
        x[sa[0]]=0;
        for(p=1,i=1;i<n;i++) x[sa[i]]=y[sa[i-1]]==y[sa[i]]&&y[sa[i-1]+j]==y[sa[i]+j]?p-1:p++;
        m=p;
    }
    return;
}

void getht(int *r,int n)
{
    int i,j,k=0;
    for(i=1;i<=n;i++) rnk[sa[i]]=i;
    for(i=0;i<n;i++)
    {
        if(k) k--;
        else k=0;
        j=sa[rnk[i]-1];
        while(r[i+k]==r[j+k]) k++;
        hgt[rnk[i]]=k;
    }
    return;
}

bool judge(int k,int n)
{
    int maxx,minn,i;
    maxx=-N,minn=N;
    for(i=2;i<=n;i++)
    {
        if(hgt[i]>=k)
        {
            maxx=max(maxx,max(sa[i-1],sa[i]));
            minn=min(minn,min(sa[i-1],sa[i]));
            if(maxx-minn>k) return true;
        }
        else maxx=-N,minn=N;
    }
    return false;
}
string ss;
int main()
{
    int t,n,i,l,r,m,ans;
    while(scanf("%d",&n)!=EOF)
    {
        // if(n==0) break;
        cin >> ss;
        for(i=0;i<n;i++) ary[i] = ss[i] - 'a';
        n--;
        for(i=0;i<n;i++) ary[i]=ary[i+1]-ary[i]+88;
        ary[n]=0;
        getsa(ary,sa,n+1,256);
        getht(ary,n);
        l=0,r=n/2,ans=0;
        while(l<=r)
        {
            m=(l+r)/2;
            if(judge(m,n)) l=m+1,ans=m;
            else r=m-1;
        }
        if (ans <= 0) cout << 0 << endl;
        else cout << ans + 1 << endl;
    }
    return 0;
}


#include <stdio.h>
int n;
char a[50];
int main(){
	scanf("%d",&n);
	scanf("%s",a);
	printf("%s",n<3200?"red":a);
}

Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

s is a string of length between 1 and 10 (inclusive).

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(ll i = 0; i < (ll)(n); i++)
#define rep2(i, a, n) for(ll i = a; i < (ll)(n); i++)
#define memi cout << endl
#define kono(n) cout << fixed << setprecision(n)
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define hina cout << ‘ ‘
const ll mei = (ll)1e9 + 7;

int main(){
  ll n;
  string s;
  cin >> n >> s;
  if(n < 3200)
    cout << "red";
  else
    cout << s;
  memi;
}


#include <bits/stdc++.h>
using namespace std;
int main(){
	int a;
	string s;
	cin >> a >> s;
  	if(a<3200)cout << "red" << endl;
  	else cout << s << endl;
}


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

 int main(){
   int a;
   string s;
   cin>>a>>s;
   if(a>=3200){
     cout<<s<<endl;
   }else{
     cout<<"red"<<endl;
   }
 }


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

int main() {
  int s;
  cin>>s;
  string a;
  cin>>a;
  if(s<=3200){
    cout<<"red"<<endl;
  }
  else{
    cout<<a<<endl;
  }
}


#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long

using namespace std;
const int MAXN = (int)(1e6) + 10;
const int MOD = (int)(1e9) + 7;
const ll INF = (ll)(1e18);

int main()
{
    ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    // Type your code here
    string s; int a;
    cin >> a >> s;
    if(a < 3200) cout << "red"; else cout << s;
    return 0;
}


#include <bits/stdc++.h>
#define FOR(i, m, n) for (int i = m; i < (n); i++)
#define FORR(i, m, n) for (int i = (m); i > 0; i--)
#define REP(i, n) FOR(i, 0, n)
#define ALL(v) v.begin(), v.end()
#define RALL(v) v.rbegin(), v.rend()
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;

int main() {
  int a;
  string s;
  cin >> a >> s;
  cout << (a >= 3200 ? s : "red") << endl;
  return 0;
}