akhauriyash/Code-Regression huggingface dataset:
// Union Find 木
package main

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

func find(parent []int, i int) int {
	if parent[i] < 0 {
		return i
	}
	parent[i] = find(parent, parent[i])
	return parent[i]
}

func unite(parent []int, i, j int) {
	i = find(parent, i)
	j = find(parent, j)
	if i == j {
		return
	}
	parent[j] += parent[i]
	parent[i] = j
}

func fill(a []int, x int) {
	for i := 0; i < len(a); i++ {
		a[i] = x
	}
}

func reverseInts(a []int) {
	l := len(a)
	for i := 0; i < l/2; i++ {
		a[i], a[l-1-i] = a[l-1-i], a[i]
	}
}

func main() {
	defer flush()

	N := readInt()
	M := readInt()
	AB := make([]struct{ A, B int }, M)
	for i := 0; i < M; i++ {
		AB[i].A = readInt() - 1
		AB[i].B = readInt() - 1
	}

	parent := make([]int, N)
	fill(parent, -1)

	inconvenience := N * (N - 1) / 2
	var result []int
	for i := M - 1; i > -1; i-- {
		a := AB[i].A
		b := AB[i].B
		result = append(result, inconvenience)
		pa := find(parent, a)
		pb := find(parent, b)
		if pa != pb {
			inconvenience -= parent[pa] * parent[pb]
		}
		unite(parent, a, b)
	}

	reverseInts(result)
	for i := 0; i < len(result); i++ {
		println(result[i])
	}
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

var stdoutWriter = bufio.NewWriter(os.Stdout)

func flush() {
	stdoutWriter.Flush()
}

func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(stdoutWriter, args...)
}


Measured memory_bytes: 10620
function compare(a, b) {
    return a - b;
}

function Main(input) {
    var NA = input.split('\n');
    var N = parseInt(NA[0]);
    var A = NA[1].split(' ').slice(0, N).map(n => parseInt(n)).sort(compare);

    console.log(Math.abs(A[0] - A[N-1]));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Measured memory_bytes: 21192
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace AtCoder
{
    class Pair
    {
        public Pair(long a,long b)
        {
            this.right = b;
            this.left = a;
        }
        public long right;
        public long left;
    }

    class Program
    {
        static void Main(string[] args)
        {
            new BG042().slove();
            #if DEBUG
                Console.WriteLine("続行するには何かキーを押してください．．．");
                Console.ReadLine();
            #endif

        }
    }

    class BG042
    {
        public void slove()
        {
            var a = getLineLongs();
            puts(s(a[0]%a[1], a[1]));
        }

        public static long s(long a,long b)
        {
            long temp = 0L;
            while (true)
            {
                temp = Math.Abs(a - b);
                if(temp > a)
                {
                    return a;
                }
                else
                {
                    a = temp;
                }
            }

        }

        public static int[] getCharInts()
        {
            //return getChar().Select(p => int.Parse(p.ToString())).ToArray();
            var a = new List<int>();
            var b = getChar();
            int i;
            for (i = 0; i < b.Count(); i++)
            {
                a.Add(int.Parse(b[i].ToString()));
            }
            return a.ToArray();
        }


        public static long[] getLineLongs()
        {
            return getLine().Select(p => long.Parse(p)).ToArray();
        }



        public static char[] getChar()
        {
            return getLine()[0].ToCharArray();
        }

        public static int[] getLineInts()
        {
            return getLine().Select(p => int.Parse(p)).ToArray();
        }

        public static String[] getLine()
        {
            String line = Console.ReadLine();
            String[] sp = line.Split(' ');
            if (sp.Length == 1)
            {
                //System.out.println(line);
                return new String[] { line };
            }
            else
            {
                return sp;
            }
        }
       

        void puts(Object mes)
        {
            Console.WriteLine(mes);
        }
    }


}

Measured memory_bytes: 13396
#include <bits/stdc++.h>
using namespace std;

int main() {
  int N, M;
  int ans=1;
  cin >> N >> M;
  int i=0;
  while(i<N){
   
    if(ans<M){
      ans *=2;
    }else{
      ans += M;
    }
    i++;
  }
  
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 256
def judge(N,L):
    max_length = 0
    max_index = -1
    for i in range(N):
        if(L[i]>max_length):
            max_length = L[i]
            max_index = i
    del L[max_index]
    
    if(sum(L)>max_length):
        return print('Yes')
    else:
        return print('No')
    
if __name__ == '__main__':
    N = int(input())
    L = input().split()
    for i in range(N):
        L[i] = int(L[i])
    judge(N,L)

Measured memory_bytes: 3064
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <limits.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <map>
#include <numeric>
#include <typeinfo>
#include <stdlib.h>


using namespace std;


int main(int argc, char* argv[]){
// 1 bubbleSort(A, N) // N 個の要素を含む 0-オリジンの配列 A
// 2   flag = 1 // 逆の隣接要素が存在する
// 3   while flag
// 4     flag = 0
// 5     for j が N-1 から 1 まで
// 6       if A[j] < A[j-1]
// 7         A[j] と A[j-1] を交換
// 8         flag = 1
//   return 0;

  int n, cnt = 0, tmp;
  cin >> n;
  std::vector<int> a(n+1);
  for (int i = 0; i < n; i++){
    cin >> a[i];
  }
  bool flag = true;
  while(flag){
    flag = false;
    for(int j=n-1; j>0; j--){
      if(a[j] < a[j-1]){
        tmp = a[j];
        a[j] = a[j-1];
        a[j-1] = tmp;
        flag = true;
        cnt ++;
      }
    }
  }
  for(int i=0; i<n-1; i++){
    cout << a[i] << " ";
  }
  cout << a[n-1] << endl;
  cout << cnt << endl;
}



Measured memory_bytes: 3100
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int num=1e9+7;

ll to_ll(string s){
    int n=s.size();
    ll tran=0;
    for(int i=0; i<n; i++){
        tran+=s[i]-'0';
        if(i!=n-1)tran*=10;
    }
    return tran;
}

int main(){
    string s;
    cin >> s;
    int n=s.size();
    vector<char> plus(n-1);
    ll sum=to_ll(s);

    for(int bit=0; bit<(1<<n-1); bit++){
        for(int i=0; i<n-1; i++){
            if(bit&(1<<i)) plus[i]='+';
            else plus[i]='n';
        }
        bool flag = true;
        for(int i=0; i<plus.size(); i++){
            if(plus[i]=='+'){
                flag=false;
                break;
            }
        }
        if(flag) continue;
        string tmp;
        tmp.push_back(s[0]);
        int ans = 0,tran = 0;
        for(int i=0; i<n-1; i++){
            if(plus[i]=='+'){
                for(int j=0; j<tmp.size(); j++){
                    tran+=tmp[j]-'0';
                    if(j!=tmp.size()-1)tran*=10;
                }
                ans += tran;
                tran = 0;
                tmp.clear();
            }
            tmp.push_back(s[i+1]);
        }
        for(int j=0; j<tmp.size(); j++){
            tran+=tmp[j]-'0';
            if(j!=tmp.size()-1)tran*=10;
        }
        ans+=tran;
        sum+=ans;
    }
    std::cout << sum << endl;
}

Measured memory_bytes: 256
MAX = 1000000

hamming_list = [False] * (MAX + 1)

hamming_list[0] = False
hamming_list[1] = True

for index in range(2, MAX + 1):

    if index % 2 == 0:
        if hamming_list[index // 2]:
            hamming_list[index] = True
    elif index % 3 == 0:
        if hamming_list[index // 3]:
            hamming_list[index] = True
    elif index % 5 == 0:
        if hamming_list[index // 5]:
            hamming_list[index] = True

while True:

    input_data = input()

    if input_data == "0":
        break

    start, end = [int(item) for item in input_data.split(" ")]

    count = sum(hamming_list[start:end + 1])
    print(count)



Measured memory_bytes: 21144
#include <iostream>
#include <cstring>

using namespace std;

bool table[1000001];

int main(){
	while(true){
		int n, a, sum = 0;
		cin >> n;
		if(n == 0){ break; }
		memset(table, 0, sizeof(bool) * 1000001);
		table[0] = true;
		while(n--){
			cin >> a;
			for(int i = sum; i >= 0; --i){
				if(table[i]){ table[i + a] = true; }
			}
			sum += a;
		}
		int answer = sum / 2;
		for(; answer >= 0; --answer){
			if(table[answer]){ break; }
		}
		cout << (sum - answer * 2) << endl;
	}
	return 0;
}

Measured memory_bytes: 0
N, K = gets.split.take(2).map(&:to_i)
A = gets.split.take(N).map(&:to_i).sort

if K > A.max
  puts :IMPOSSIBLE
  exit
end

a = A.dup
while a.size > 1 && a[0] > 1
  b = a.pop - a[-1]
  if b > 0
    a[a.bsearch_index{|v|v>b}||a.size, 0] = b
  end
end

A.select{|n| n >= K}.each{|n|
  if (n - K) % a[0] == 0
    puts :POSSIBLE
    exit
  end
}
puts :IMPOSSIBLE


Measured memory_bytes: 13048
#define _CRT_SECURE_NO_WARNINGS

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

using namespace std;

#define LL long long

int n,k,w[100001];

int main() {
	cin>>n>>k;
	for(int i=0;i<n;i++)cin>>w[i];
	
	int hi=1100000000,lo=0;
	while(hi-lo>1){
		int mid=(hi+lo)/2;
		int now = 0;
		for(int i=0;i<k;i++){
			int add=0;
			while(now<n && add+w[now]<=mid){
				add+=w[now];
				now++;
			}
		}
		if(now==n)hi=mid;//ok
		else lo=mid;//ng
	}
	cout<<hi<<endl;
	return 0;
}




Measured memory_bytes: 3504
#include <bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<(b);++i)
#define erep(i,a,b) for(int i=a;i<=(int)(b);++i)
#define per(i,a,b) for(int i=(b);i>(a);--i)
#define eper(i,a,b) for(int i=((int)(a));i>=b;--i)
#define pb push_back
#define mp make_pair
#define INF (1<<30)-1
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int dy[]={0, 0, 1, -1};
int dx[]={1, -1, 0, 0};
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int lcm(int a,int b){return a/gcd(a, b)*b;}

ll n, x, a[100050], ans;
int main() {
 ios::sync_with_stdio ( false );
 cin.tie ( 0 );
    cin >> n >> x;
    rep(i, 0, n) cin >> a[i];
    if (a[0] > x) {
        ans = a[0] - x;
        a[0] = x;
    }
    rep(i, 1, n) {
        if (a[i] + a[i-1] > x) {
            ans += (a[i] + a[i-1] - x);
            a[i] -= (a[i] + a[i-1] - x);
        }
    }
    printf("%lld\n", ans);
    return 0;
}


Measured memory_bytes: 1024
#include <stdio.h>
 
int main()
{
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
 
    int i, cnt = 0;
    for( i = a; i <= b; ++i )
        if( c % i == 0 )
            ++cnt;
 
    printf("%d\n", cnt);
 
    return 0;
}

Measured memory_bytes: 596
//  cd Desktop/Atcoder
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define rep(i,n) for(i=0;i<(n);i++)
#define ll long long
#define ull unsigned long long
#define MOD 1000000007
#define MYPOW_t ull

MYPOW_t Mypow(MYPOW_t x,MYPOW_t n){
    MYPOW_t ret=1;
    while (n>0) {
        if (n&1) ret=(ret*x)%MOD;
        x=(x*x)%MOD;
        n>>=1;
    }
    return ret;
}

int Max(int a, int b) { return a > b ? a : b; }

int main(){
    ull x,y,i,j,n,dn=0,X,Y,ans=0,I=1,DN=1,I_DN=1;
    scanf("%lld%lld",&x,&y);
    n=Max(x,y);
    rep(i,n+1){
        if (i!=0){
            I*=i;I%=MOD;
        }
        I_DN=I;
        X=i;Y=i*2;dn=0;DN=1;
        if ((x-X)%2==0){
            if ((x-X)/2==y-Y){
                dn=y-Y;
                rep(j,dn){
                    DN*=(j+1)%MOD;DN%=MOD;
                    I_DN*=(i+j+1)%MOD;I_DN%=MOD;
                }
                ans+=(I_DN*Mypow((I*DN)%MOD,MOD-2))%MOD;
                ans%=MOD;
            }
        }
    }
    printf("%lld",ans%MOD);
    return 0;
}


Measured memory_bytes: 1720
/*author: hyperion_1724
  date: 
*/
 
//Required Libraries
 
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
 
//Required namespaces
 
using namespace std;
using namespace __gnu_pbds;
 
//Required defines
 
#define endl '\n'
 
#define READ(X) cin>>X;
#define READV(X) long long X; cin>>X;
#define READAR(A,N) long long A[N]; for(long long i=0;i<N;i++) {cin>>A[i];}
#define rz(A,N) A.resize(N);
#define sz(X) (long long)(X.size())
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define trav(x,A) for(auto &x:A)
#define veci vector<int>
#define vecl vector<long long>
#define FORI(a,b,c) for(long long a=b;a<c;a++)
#define FORD(a,b,c) for(long long a=b;a>c;a--)
 
//Required typedefs
 
typedef tree<long long,null_type,less<long long>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
typedef tree<long long,null_type,greater<long long>,rb_tree_tag,tree_order_statistics_node_update> ordered_set1;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<long,long> pll;
 
//Required Constants
 
const long long inf=(long long)1e18;
const long long MOD=(long long)(1e9+7);
const long long INIT=(long long)(5000+1);
 
//Required Functions
 
ll power(ll x,ll y) 
{ 
    if (y == 0) 
        return 1; 
    ll p = power(x, y/2) % MOD; 
    p = (p * p) % MOD; 
  
    return (y%2 == 0)? p : (x * p) % MOD; 
}
ll modInverse(ll a) 
{ 
   return power(a,MOD-2); 
   
}
 
//Work
 
ll dp[INIT][INIT][2]={0};
ll A[INIT]={0};
 
ll make(ll l,ll r,ll c)
{
	if (dp[l][r][c]!=-inf)
	{
		return dp[l][r][c];
	}
	if (l==r)
	{
		dp[l][r][1]=A[l];
		dp[l][r][0]=0;
	}
	else if(l<r)
	{
		if (A[l]+make(l+1,r,0) >= A[r]+make(l,r-1,0))
		{
			dp[l][r][1]=A[l]+make(l+1,r,0);
			dp[l][r][0]=make(l+1,r,1);
		}
		else
		{
			dp[l][r][1]=A[r]+make(l,r-1,0);
			dp[l][r][0]=make(l,r-1,1);
		}
	}
	return dp[l][r][c];
}
 
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
 
 
    FORI(i,0,INIT)
    {
    	FORI(j,0,INIT)
    	{
    		dp[i][j][0]=-inf;
    		dp[i][j][1]=-inf;
    	}
    }
	READV(N);
	FORI(i,1,N+1)
	{
		READ(A[i]);
	}
	ll ans=make(1,N,1)-make(1,N,0);
	cout<<ans<<endl;
 
	return 0;
}

Measured memory_bytes: 391296
from collections import deque

n = int(input())
e = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    e[a].append(b)
    e[b].append(a)
l = sorted(list(map(int,input().split())),reverse=True)
ans = [-1]*n
for i in range(n):
    if len(e[i]) == 1:
        q = deque([])
        q.append(i)
        ans[i] = l[0]
        now = 1
        while q:
            b = q.popleft()
            for nex in e[b]:
                if ans[nex] == -1:
                    ans[nex] = l[now]
                    now += 1
                    q.append(nex)
        count = 0
        for j in range(n):
            for k in e[j]:
                count += min(ans[j],ans[k])
        print(count//2)
        print(*ans)
        exit()





Measured memory_bytes: 12000
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {
    private static String solve(Scanner scanner) {
        int N = Integer.parseInt(scanner.nextLine());
        String[] nums = scanner.nextLine().split(" ");

        LinkedList<String> result = new LinkedList<>();

        for (int i = 0; i < N; i ++) {
            if (i % 2 == 1) {
                result.addLast(nums[i]);
            } else {
                result.addFirst(nums[i]);
            }
        }

        if (N % 2 == 0) {
            Collections.reverse(result);
        }

        return result.stream().collect(Collectors.joining(" "));
    }

    private static final String ex1 = "4\n" +
            "1 2 3 4";
    private static final String ex2 = "3\n" +
            "1 2 3";
    private static final String ex3 = "1\n" +
            "1000000000";
    private static final String ex4 = "6\n" +
            "0 6 7 6 7 0";

    public static void main(String[] args) {
//        System.out.println(solve(new Scanner(ex1)));
//        System.out.println(solve(new Scanner(ex2)));
//        System.out.println(solve(new Scanner(ex3)));
//        System.out.println(solve(new Scanner(ex4)));

        System.out.println(solve(new Scanner(System.in)));
    }

    private static int[] lineToIntNums(String line) {
        String[] strNums = line.split(" ");
        int[] ret = new int[strNums.length];
        for (int i = 0; i < strNums.length; i ++) {
            ret[i] = Integer.parseInt(strNums[i]);
        }
        return ret;
    }

    private static long[] lineToLongNums(String line) {
        String[] strNums = line.split(" ");
        long[] ret = new long[strNums.length];
        for (int i = 0; i < strNums.length; i ++) {
            ret[i] = Long.parseLong(strNums[i]);
        }
        return ret;
    }
}


Measured memory_bytes: 82972
#include <iostream>
#include <iomanip>
#include <fstream>

#include <string>
#include <array>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>

#include <bitset>
#include <tuple>
#include <cmath>
#include <complex>
#include <algorithm>
#include <utility>
#include <regex>

#include <cstdint>
#include <numeric>
#include <functional>
#include <cassert>

using namespace std;
using ll = int64_t;
using ull = uint64_t;

constexpr ll INF = 1000000000;/* 1e+9a */

void solve(istream &cin) {
    ll A, B;
    cin >> A >> B;
    if(!cin) return;
    if(B % A == 0){
        cout << A + B << endl;
    }
    else{
        cout << B - A << endl;
    }
    
}

int main(int argc, char *argv[]) {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << setprecision(16) << scientific;
#ifdef DEBUG
    cerr << "DEBUG MODE" << endl;
    string test_cases = "test.txt";
    auto fs = fstream(test_cases, fstream::in);
    while(fs) {
        solve(fs);
    }
#else
    solve(cin);
#endif
}


Measured memory_bytes: 256
import java.util.*;

public class Main{
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int M = sc.nextInt();
    int X = sc.nextInt();
    int[] arr = new int[N+1];
    for(int i = 0; i<M; i++){
        int idx = sc.nextInt();
        arr[idx] = 1;
    }
    for(int i = X+1; i<N; i++){
      arr[i+1] += arr[i];
    }
    for(int i = X-1; i>0; i--){
      arr[i-1] += arr[i];
    }
    int res = Math.min(arr[0],arr[N]);
    System.out.println(res);
  }
}

Measured memory_bytes: 21844
#include <iostream>
using namespace std;
#pragma warning (disable: 4996)

int M, D, cnt;

int main() {
	cin >> M >> D;
	for (int i = 1; i <= M; i++) {
		for (int j = 1; j <= D; j++) {
			int A = i, B = (j / 10), C = (j % 10);
			if (A >= 2 && B >= 2 && C >= 2 && A == B * C) cnt++;
		}
	}
	cout << cnt << endl;
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> ii;
typedef tuple<ll, ll, ll> iii;
typedef vector<ll> vi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
#define REP(i,n) for (ll i = 0; i < n; ++i)
#define REPR(i,n) for (ll i = n-1; i >= 0; --i)
#define FOR(i,m,n) for (ll i = m; i < n; ++i)
#define FORR(i,m,n) for (ll i = n-1; i >= m; --i)
#define FORE(x,xs) for (const auto& x : xs)
#define FORI(i,v) for (auto i = v.begin(); i != v.end(); i++)
#define ALL(v) v.begin(), v.end()
#define CHMIN(x,y) x = min(x, y)
#define CHMAX(x,y) x = max(x, y)

const ll INF = 1ll<<61;

template<typename T> using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;

class Dijkstra {
private:
    int N;
    vvii E;

    void init(int n) {
        E.resize(0); E.clear();
        N = n; E.resize(n);
    }

public:
    Dijkstra() {}
    Dijkstra(int n) { init(n); }

    void add(int from, int to, int cost) {
        E[from].push_back(ii(to, cost));
    }

    vi solve(int s) {
        vi dis(N, INF);
        vector<bool> vis(N);
        dis[s] = 0;

        min_priority_queue<ii> q;
        q.push(ii(0, s));

        while (!q.empty()) {
            int t, d;
            tie(d, t) = q.top(); q.pop();

            if (vis[t]) continue;
            vis[t] = true;

            FORE (p, E[t]) {
                ll next = p.first, c = p.second;
                if (vis[next]) continue;
                if (dis[t] + c < dis[next]) {
                    dis[next] = dis[t] + c;
                    q.push(ii(dis[next], next));
                } else if (dis[t] + c == dis[next]) {
                }
            }
        }
        return dis;
    }
};

int N, M;

ll solve() {
    Dijkstra dijkstra(N);
    REP (i, N-1) dijkstra.add(i+1, i, 0);

    REP (m, M) {
        ll l, r, c;
        cin >> l >> r >> c;
        dijkstra.add(l-1, r-1, c);
    }

    ll ans = dijkstra.solve(0)[N-1];
    if (ans >= INF) ans = -1;
    return ans;
}

int main() {
    cin >> N >> M;
    cout << solve() << endl;
}

Measured memory_bytes: 10104
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define setbits(x) __builtin_popcount(x)
#define setbitsll(x) __builtin_popcountll(x)
#define endl '\n'
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define se second
#define fi first
#define pai acos(-1)
#define fn(i,x) for(i=0;i<x;i++)
#define fs(i,s,x) for(i=s;i<x;i++)
#define fr(i,x,s) for(i=x;i>=s;i--)
#define fit(itr,s) for(itr=s.begin();itr!=s.end();itr++)
#define W while
#define pp pair<ll,ll>
#define ppi pair<int,int>
#define vl vector<ll>
#define vll vector<pp >
#define vi vector<int>
#define vii vector<ppi>
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define debug(x) cerr<<#x<<" :: "<<x<<endl;
#define debug2(x,y) cerr<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<endl;
#define debug3(x,y,z) cerr<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\t"<<#z<<" :: "<<z<<endl;
#define debug4(x,y,z,w) cerr<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\t"<<#z<<" :: "<<z<<"\t"<<#w<<" :: "<<w<<endl;
#define boost  ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
const ll MAX=1e16;
const ll MM=1e18;
const ll mod=998244353;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};

ll expo(ll x,ll n,ll M=mod)
{
    ll ans=1;
    while(n>0)
    {
        if(n&1){ans=(ans*x)%M;}
                x=(x*x)%M;
                n>>=1;
    }
    return ans;
}
const ll MaxSize = 3e5;
ll facts[MaxSize], invFacts[MaxSize];

void preproc() {
  facts[0] = 1;
  for (int i = 1; i < MaxSize; i++) {
    facts[i] = ((ll)facts[i - 1] * i) % mod;
  }
  invFacts[MaxSize - 1] = expo(facts[MaxSize - 1], mod - 2,mod);

  for (int i = MaxSize - 2; i >= 0; i--) {
    invFacts[i] = ((ll)invFacts[i + 1] * (i + 1)) % mod;
  }
}

ll combination(ll n, ll k) {
  if(n<k) return 0;
  ll res = facts[n];
  res = ((ll)res * invFacts[k]) % mod;
  return ((ll)res * invFacts[n - k]) % mod;
}

////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////

ll n, m,  q;
ll a[60], b[60], c[60], d[60];
ll ans = 0;

void check(vl &v) {
    ll now = 0;
    for(int i = 0; i < q; i++) {
        if(v[b[i]]  - v[a[i]] == c[i]) {
            now += d[i];
        }
    }

    ans = max(now, ans);
}
void dfs(ll depth, vl &v) {
    if(depth == n) {
        check(v);
        return;
    }
    for(ll i = v[depth-1]; i <= m; i++) {
        v[depth] = i;
        dfs(depth+1, v);
    }
}
void solve()
{
    
    cin >> n >> m >> q;    
   
    
    vl v(n);
    for(ll i = 0; i < q; i++) {
        cin >> a[i] >>  b[i] >> c[i] >> d[i];
        a[i]--;
        b[i]--;
    }
    for(int i = 1; i <= m; i++) {
        v[0] = 1;
        dfs(1, v);
    }
    cout << ans  << endl;
} 
int main()
{
  boost;
  int m;
  //cin >> m;
  int t=1;
  //cin>>t;
  while(t--)
  {
      solve();
  }
}



Measured memory_bytes: 3624
#include <bits/stdc++.h>
using namespace std;
long long d[5001];
long long D[5001];
long long a[5001];
long long b[5001];
int main()
{
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    long long k,q;
    cin>>k>>q;
    int i,j;
    for(i=0 ; i<k ; i++)cin>>d[i];
    for(i=0 ; i<q ; i++){
        long long n,x,m;
        b[-1]=0;
        cin>>n>>x>>m;
        for(j=0 ;j<k ; j++){
            a[j]=d[j]%m;
            if(j==0)b[j]=a[j];
            else b[j]=b[j-1]+a[j];
        }

        long long t=x+(n-1)/k*b[k-1]+(k==1 ? 0 :b[(n-1)%k-1]);
        long long cnt=0;
        for(j=0 ; j<k ; j++){
            if(a[j]==0)cnt--;
        }
        cnt*=(n-1)/k;
        if(k!=1)
        for(j=0 ; j<=(n-1)%k-1 ; j++)if(a[j]==0)cnt--;

        cout<<n-1-(t/m-x/m)+cnt<<"\n";
    }
    return 0;
}


Measured memory_bytes: 384
import Control.Applicative
import Control.Monad

multiplyMatrix :: [[Int]] -> [Int] -> [Int]
multiplyMatrix a v = map (sum . zipWith (*) v) a

main = do
    [n, m] <- (map (read :: String -> Int) . words) <$> getLine
    a <- replicateM n ((map read . words) <$> getLine)
    v <- (map read . lines) <$> getContents
    putStr $ unlines $ map show $ multiplyMatrix a v

Measured memory_bytes: 7592
#include <bits/stdc++.h>

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

using namespace std;

const int INF = 2e9 + 7;


int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int a;
    cin >> a;
    cout << (int) (ceil(a / 2.0));
    return 0;
}


Measured memory_bytes: 256
#include<stdio.h>
int main()
{
    int A,B,C,D,sum1,sum2,r;
    scanf("%d %d %d %d",&A,&B,&C,&D);
    sum1=A*B;
    sum2=C*D;
    if(sum2<sum1){
        printf("%d",sum1);
    }
    else if (sum1==sum2){
        printf("%d",sum1);
    }

    else {
        printf("%d",sum2);
    }



    return 0;
}


Measured memory_bytes: 128
#![allow(non_snake_case)]
fn main() {
    let s = std::io::stdin();
    let mut sc = Scanner { stdin: s.lock() };
    let M:usize = sc.read();
    let nums:Vec<(usize, usize)> = (0..M).map(|_| (sc.read(), sc.read())).collect();
    let mut red:Vec<usize> = vec![];
    let mut ans:usize = 0;
    for i in 0..M{
        let d = nums[i].0;
        let mut c = nums[i].1;
        ans += (c-1)/9*(d+9);
        c = c - (c-1)/9*9;
        for _ in 0..c{
            red.push(d);
        }
    }
    let mut now = red[0];
    for i in 1..(red.len()){
        now += red[i];
        ans += 1;
        if now > 9{
            now = (now/10)+(now%10);
            ans += 1;
        }
    }
    println!("{}", ans);

}

pub struct Scanner<R> {
    stdin: R,
}

impl<R: std::io::Read> Scanner<R> {
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n')
            .take_while(|&b| b != b' ' && b != b'\n')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
        .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}




Measured memory_bytes: 17652
#include <iostream>
#include <string>
#include <limits.h>
#include <numeric>
#include <math.h>
#include <bits/stdc++.h>
#define rep(i,c) for (int i=0;i<c;i++)
using namespace std;
typedef long long ll;
 
 
int main(){
    int N,K;
    cin >> N>>K;
    int x[N];
    rep(i,N)cin >> x[i];
    int min=0;
    int total=0;
    rep(i,N){
        
        int cost_a = 2*(x[i]-0);
        int cost_b = 2*(K-x[i]);
        if(cost_a>cost_b)  min= cost_b;
        else min = cost_a;
        total += min;
    }
    cout << total << endl;


}

Measured memory_bytes: 256
import java.util.*;
import java.util.stream.Collectors;
 
 
public class Main {
    public static void main(String[] args) {
    	
        Scanner scanner=new Scanner(System.in);
        
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        
        if(a<=8&&b<=8)
        	System.out.println("Yay!");
        else
        	System.out.println(":(");
        
 
 
    }
 
}


Measured memory_bytes: 20820
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

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


	int N = getint(), K = getint();
	int dp[101], h[101] = {};
	dp[K] = 0;
	rep(i, K) dp[i] = 1e9;
	h[K] = getint();

	int k[101];
	rep(i, K + 1) k[i] = i;
	rep(i, N - 1) {
		rep(j, K + 1) k[j] = (k[j] + K) % (K + 1);
		h[k[K]] = getint();
		dp[k[K]] = 1e9;
		rep(j, K) chmin(dp[k[K]], dp[k[j]] + abs(h[k[j]] - h[k[K]]));
	}

	printf("%d", dp[k[K]]);

	Would you please return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;

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

int main()
{
    long long sum = 0;
    int k;
    cin >> k;
    for (int i = 1; i <= k; i++) {
        for (int j = 1; j <= k; j++) {
            for (int l = 1; l <= k; l++) {
                sum += __gcd(i, __gcd(j, l));
            }
        }
    }
    cout << sum << endl;
    return 0;
}

Measured memory_bytes: 3632
import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
		int sum=0;
		while(sc.hasNext()){
			char[] c=sc.next().toCharArray();
			for(int i=0;i<c.length;i++){
				if(intJudge(c[i])){
					String str=c[i]+"";
					for(int j=i+1;j<c.length;j++){
						if(intJudge(c[j])){
							str+=(c[j]+"");
						}else{
							break;
						}
						i=j;
					}
					sum+=Integer.parseInt(str);
				}
			}
		}
		System.out.println(sum);
	}
	static boolean intJudge(char c){
		try{
			Integer.parseInt(c+"");
			return true;
		}catch(NumberFormatException e){
			return false;
		}
	}
}

Measured memory_bytes: 17440
#include <iostream>
#include <vector>
#include <utility>

using namespace std;
using P = pair<int,int>;

int main() {
    int n,h;
    cin >> n >> h;
    vector<P> ab;
    for (int i=0; i<n; i++) {
        int a,b;
        cin >> a >> b;
        ab.emplace_back(a,b);
    }

    sort(ab.begin(), ab.end());
    P _max = ab.back();
    ab.pop_back();

    auto cmp = [](const P& x, const P& y){return x.second<y.second;};
    sort(ab.begin(), ab.end(), cmp);

    int ans = 0;
    while(h > 0) {
        ans++;
        if (h - _max.second <= 0) h -= _max.second;
        else if (!ab.empty() && _max.first < ab.back().second) {
            h -= ab.back().second;
            ab.pop_back();
        } else {
            int c = ((h - _max.second + _max.first - 1) / _max.first );
            h -= c * _max.first;
            ans += c - 1;
        }
    }
    cout << ans << endl;
}
/*
 * 1000000000
 *   99999999
 */

Measured memory_bytes: 1400
#include<bits/stdc++.h>
#define ll          long long int
#define pb          push_back
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define Max(a,b)    ((a)>(b)?(a):(b))
#define Min(a,b)    ((a)<(b)?(a):(b))
#define rep(i,a,b)  for (__typeof((b)) i=(a);i<(b);i+=1)
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (int)x.size()
#define hell        1000000007
#define endl        '\n'
#define debug(a)    cerr<<#a<<": ";for(auto i:a)cerr<<i<<" ";cerr<<'\n';
using namespace std;

void solve(){
    int a,b;
    cin>>a>>b;
    if(0<=b && 0>=a){
        cout<<"Zero";
    }
    else if(a>0){
        cout<<"Positive";
    }
    else{
        b=min(-1,b);
        cout<<((b-a)%2==0?"Negative":"Positive");
    }
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t=1;
//	cin>>t;
	while(t--){
		solve();
	}
	return 0;
}


Measured memory_bytes: 256
import sys
from heapq import heappop, heappush
from operator import itemgetter
from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 10**9 + 7
INF = float('inf')

def sol():
    N, K = map(int, input().split())
    S = input().rstrip()

    if N == 1:
        print(0)
        return

    # N - 連結成分数
    # 1回の反転で，連結成分数は1または2減る
    # 反転箇所が端の場合は1でそれ以外は2
    # 中央から順に反転

    ans = 0
    for i in range(N - 1):
        if S[i] == S[i + 1] == 'R':
            ans += 1
    for i in range(1, N):
        if S[i] == S[i - 1] == 'L':
            ans += 1

    for _ in range(K):
        if ans < N - 2:
            ans += 2
        elif ans == N - 2:
            ans += 1
        elif ans == N - 1:
            break

    print(ans)

sol()

Measured memory_bytes: 3584
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
using llong = long long;
using ullong = unsigned long long;

int main() {
  int N;
  cin >> N;
  cout << double(int(double(N)/2.0 + 0.5)) / double(N) << endl;
}


Measured memory_bytes: 256
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
#include<climits>
#include<string>
#include<set>
#include<numeric>
#include<map>
#include<iostream>
using namespace std;
#define rep(i,n) for(int i = 0;i<((int)(n));i++)
#define reg(i,a,b) for(int i = ((int)(a));i<=((int)(b));i++)
#define irep(i,n) for(int i = ((int)(n)-1);i>=0;i--)
#define ireg(i,a,b) for(int i = ((int)(b));i>=((int)(a));i--)
typedef long long ll;
typedef pair<ll, ll> mp;
ll MOD = 1e9+7;
ll inf=1e9;
//LLONG_MIN

//WA

int main(void){
	ll W,H,N,t,b=0,l=0,r,x,y,a,ans;
	cin>>W>>H>>N;
	t=H;
	r=W;
	rep(i,N){
		cin>>x>>y>>a;
		if(a==1){
			l = max(l,x);
		}else if(a==2){
			r = min(r,x);
		}else if(a==3){
			b = max(b,y);
		}else if(a==4){
			t = min(t,y);
		}
	}
	ans=(r-l)*(t-b);
	if(l>=r)ans=0;
	if(b>=t)ans=0;
	// printf("%lld,%lld,%lld,%lld\n",l,r,t,b);
	printf("%lld\n",ans);
	return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
static const int MAX = 200000;

int main()
{
	int a, b;
	char op;
	cin >> a >> op >> b;
	if (op == '+') {
		cout << a + b << endl;
	}
	else {
		cout << a - b << endl;
	}

    return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
  int N;
  cin >> N;
  
  int V[12];
  for (int i=0; i<N; i++) cin >> V[i];
  sort(V,V+N,greater<int>());
  int sum = 0;
  for (int i=1; i<N; i++) {
    sum += V[i];
  }
  cout << sum + V[0] / 2 << endl;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;

int main(){
    int ans = 0;
    string s;

    cin >> s;
    
    for(int i = 0; i < 3; ++i){
        if(s[i] == '1'){
            ans++;
        }
    }

    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 256
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x
    
    def size(self, x):
        return -self.parents[self.find(x)]
        
    def same(self, x, y):
        return self.find(x) == self.find(y)
    
    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
    
    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())
    
    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}
    
    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def main():
    N, M = map(int, input().split())
    p = list(map(int, input().split()))
    p = [i-1 for i in p]
    u = UnionFind(N)
    for _ in range(M):
        x, y = map(int, input().split())
        x -= 1
        y -= 1
        u.union(x, y)
    r = 0
    for i in range(N):
        if u.same(p[i], i):
            r += 1
    return r
print(main()) 


Measured memory_bytes: 13940
program main
  implicit none
  integer i, ans
  character(4) S
  !read(*, *) (L(i), i = 1,N)
  read(*, *) S
  ans = 0
  do i = 1,3
    if (S(i:i) == S(i+1:i+1)) then
      ans = 1
    end if
  end do
  if (ans == 1) then
    write(*, *) 'Bad'
  else
    write(*, *) 'Good'
  end if
end program main


Measured memory_bytes: 256
import sys

import numpy as np
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
INF = float("INF")
mod = 10 ** 9 + 7
"""dd = [(-1, 0), (0, 1), (1, 0), (0, -1)];
ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)];
ddn9 = ddn + [(0, 0)]
for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""

def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]  # WideIntPoint
def ws(): return sys.stdin.readline().split()
def si(): return int(sys.stdin.readline())  # SingleInt
def ss(): return input()
def hi(n): return [si() for _ in range(n)]
def hs(n): return [ss() for _ in range(n)]  # HeightString
def s_list(): return list(input())
def mi(n): return [wi() for _ in range(n)]  # MatrixInt
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]
def num_grid(n): return [[int(i) for i in sys.stdin.readline().split()[0]] for _ in range(n)]  # NumberGrid
def grid(n): return [s_list() for _ in range(n)]


def main():
    n = int(input())
    root_n = np.sqrt(n)
    root_n = int(root_n)
    ans = 10**10
    for i in range(1,root_n+1):
        if n % i == 0:
            b = n // i
            str_b = str(b)
            ans = min(ans, len(str_b))
    print(ans)


if __name__ == '__main__':
    main()

Measured memory_bytes: 23568
#include <iostream>
#include<algorithm>
#include <vector>
#include<string>
#include<cmath>
#include<cstdio>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define max(x,y) (((x)>(y)) ? x:y)
#define min(x,y) (((x)<(y)) ? x:y)
#define FOR(a,b,c) for(b=(c);b<(a);b++)
#define ender {return 0;}
#define tosasuretu(a) (a*(a+1)/2)
inline ll kaizyo(ll);
ll combination(ll, ll);
int main() {
	int n, i;
	cin >> n >> i;
	cout << (n - i) + 1;
	return 0;
}


inline ll kaizyo(ll x) {
	long ans = 1;
	for (int z = 0; z < x; z++) {
		ans *= (x - z);
	}
	return ans;
}


Measured memory_bytes: 764
#include <bits/stdc++.h>

using namespace std;

vector <long long> V;

void gen(long long n)
{
    if (n > 3234566667) return;
    V.push_back(n);
    int g = n % 10;
    if (g) gen(n * 10 + g - 1);
    gen(n * 10 + g);
    if (g < 9) gen(n * 10 + g + 1);
}

int main()
{
//    freopen("TEST.INP", "r", stdin);
    for (int i = 1; i <= 9; ++i) gen(i);
    sort(V.begin(), V.end());
    int k;
    cin >> k;
    cout << V[k - 1];
    return 0;
}


Measured memory_bytes: 1400
#include <bits/stdc++.h>
using namespace std;
int main(){
  int a,b ;
  cin >> a >> b;
  int c;
   c = a * b % 2;
    
    if (c == 0){
      cout << "Even" << endl;
    }
  
  else {
    cout << "Odd" << endl;
  }
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;

#ifdef SG
	#include <debug.h>
#else
	#define show(...)
	#define debug(...)
	#define deepen(...)
	#define timer(...)
#endif

#define ARG4(_1,_2,_3,_4,...) _4

#define forn3(i,l,r) for (int i = int(l); i < int(r); ++i)
#define forn2(i,n) forn3 (i, 0, n)
#define forn(...) ARG4(__VA_ARGS__, forn3, forn2) (__VA_ARGS__)

#define ford3(i,l,r) for (int i = int(r) - 1; i >= int(l); --i)
#define ford2(i,n) ford3 (i, 0, n)
#define ford(...) ARG4(__VA_ARGS__, ford3, ford2) (__VA_ARGS__)

#define forv(i,v) for (auto i = v.begin(); i != v.end(); ++i)
#define forr(i,v) for (auto i = v.end(); i != v.begin() && (--i, 1); )
#define ve vector
#define pa pair
#define tu tuple
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define fs first
#define sc second
#define all(a) (a).begin(), (a).end()
#define sz(a) ((int)(a).size())

typedef long double ld;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int ui;
typedef unsigned char uc;
typedef pa<int, int> pii;
typedef pa<int, ll> pil;
typedef pa<ll, int> pli;
typedef pa<ll, ll> pll;
typedef ve<int> vi;

const ld pi = 3.1415926535897932384626433832795l;

template<typename T> inline auto sqr (T x) -> decltype(x * x) {return x * x;}
template<typename T> inline T abs (T x) {return x > T() ? x : -x;}
template<typename T1, typename T2> inline bool umx (T1& a, T2 b) {if (a < b) {a = b; return 1;} return 0;}
template<typename T1, typename T2> inline bool umn (T1& a, T2 b) {if (b < a) {a = b; return 1;} return 0;}

int main () {
	//std::ios::sync_with_stdio(false);
    //std::cin.tie(nullptr);
	cout.setf(ios::showpoint | ios::fixed);
	cout.precision(20);
#ifdef SG
	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);
#endif
	string s;
	ll k;
	cin >> s >> k;
	int n = sz(s);
	ve<ll> a;
	for (int i = 0; i < n;) {
		int j = i;
		for (; j < n && s[i] == s[j]; ++j);
		a.pb(j - i);
		i = j;
	}
	ll res = 0;
	forn(i, sz(a)) {
		res += a[i] / 2;
	}
	ll ans = 1ll * res * k;
	if (sz(a) == 1) {
		ans = sz(s) * k / 2;
	} else if (s[0] == s[n - 1] && sz(a) > 1) {
		ans -= 1ll * k * (a[0] / 2 + a.back() / 2);
		ans += a[0] / 2 + a.back() / 2;
		ans += 1ll * (k - 1) * ((a[0] + a.back()) / 2);
	}

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


Measured memory_bytes: 256
#include <cstdio>
#include <iostream>
using namespace std;

int main() {
	while (true) {
		int H, W;
		cin >> W >> H;
		if (W == 0 && H == 0) {
			break;
		}
		for (int i = 1; i <= W; i++) {
			for (int j = 1; j <= H; j++) {
				if (1 < i&&i < W && 1 < j&& j < H) {
					cout << ".";
				}
				else {
					cout << "#";
				}
			}
			cout << endl;
		}
		cout << endl;
	}
	return 0;
}

Measured memory_bytes: 3064
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<string>
#include<stack>

using namespace std;

struct Node {
	int key;
	Node *left, *right, *parent;
	bool visited;
};

Node *root, *NIL;

void insert(int k) {
	Node *y = NIL;
	Node *x = root;
	Node *z;
	z = (Node*) malloc(sizeof(Node));
	z->key = k;
	z->left = NIL;
	z->right = NIL;
	while (x != NIL) {
		y = x;
		if (z->key < x->key) {
			x = x->left;
		} else {
			x = x->right;
		}
	}
	z->parent = y;
	if (y == NIL) {
		root = z;
	} else {
		if (z->key < y->key) {
			y->left = z;
		} else {
			y->right = z;
		}
	}
}

Node* find(int key) {
	Node *x = root;
	while (x != NIL) {
		if (key == x->key) {
			return x;
		} else if (key < x->key) {
			x = x->left;
		} else {
			x = x->right;
		}
	}
	return NIL;
}

void resetVisitedFlag() {
	stack<Node*> st;
	st.push(root);
	while (st.size() != 0) {
		Node *cur = st.top();
		st.pop();
		if (cur != NIL) {
			cur->visited = false;
			st.push(cur->left);
			st.push(cur->right);
		}
	}
}

void inOrder() {
	resetVisitedFlag();
	stack<Node*> st;
	st.push(root);
	while (st.size() != 0) {
		Node* cur = st.top()->left;
		while (cur != NIL && !cur->visited) {
			st.push(cur);
			cur = cur->left;
		}
		cur = st.top();
		st.pop();
		cout << " " << cur->key;
		cur->visited = true;
		Node *right = cur->right;
		if (right != NIL && !right->visited) {
			st.push(right);
		}
	}
	cout << endl;
}

void preOrder() {
	stack<Node*> st;
	st.push(root);
	while (st.size() != 0) {
		Node *cur = st.top();
		st.pop();
		if (cur != NIL) {
			cout << " " << cur->key;
			st.push(cur->right);
			st.push(cur->left);
		}
	}
	cout << endl;
}

int main() {
	int n, k;
	cin >> n;
	for (int i = 0; i < n; i++) {
		string cmd;
		cin >> cmd;
		if (cmd == "insert") {
			cin >> k;
			insert(k);
		} else if (cmd == "find") {
			cin >> k;
			if (find(k) != NIL) {
				cout << "yes" << endl;
			} else {
				cout << "no" << endl;
			}
		} else if (cmd == "print") {
			inOrder();
			preOrder();
		}
	}
	return 0;
}



Measured memory_bytes: 26536
#include<bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int,int>pi;
#define elif else if
#define rep(x,y) for(int i=x;i<y;i++)
#define REP(x,y) for(int j=x;j<y;j++)
#define Rep(x,y) for(int k=x;k<y;k++)
#define all(x) x.begin(),x.end()
#define pb push_back
#define vint vector<int>
#define vvint vector<vector<int>>
#define vtr vector<string>
#define vouble vector<double>
#define vvtr vector<vector<string>>
#define vhar vector<char>
#define vvhar vector<vector<char>>
#define mis map<int,str>
#define msi map<str,int>
#define mid map<int,double>
#define mod 100000007
#define elif else if
#define str string
int digitsum(int a){
  int b=0;
  while(a){
    b+=a%10;
    a/=10;
  }
  return b;
}
signed main(){
  int k,n,m,c=0,c2=0;
  string s,t;
  char C;
  double d;
  cin>>k>>n>>m;
  rep(n,m+1){
    if(i%k==0){
      cout<<"OK"<<endl;
      c++;
      break;
    }
  }
  if(c==0)cout<<"NG"<<endl;
}


Measured memory_bytes: 3628
function Main(input) {
	var inputArr = input.split("\n");
	var n = parseInt(inputArr[0]);
	var a = inputArr[1].split(" ");
    var sum = 0;
    var count = 0;
    var in0 = false;
    var min = 9999999999;
  
    var obj = {};
	for (var i = 0; i < n ; i++) {
      var ai = Math.abs(a[i]);
      if (a[i] < 0) {
        count++;
      }
      if (a[i] === 0) {
        in0 = true;
      }
      if (ai < min) {
        min = ai;
      }
      sum = sum + ai;
    }
    if (count % 2 === 0 || in0 === true) {
        console.log(sum) ;
    } else {
        console.log(sum - min - min) ;
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));



Measured memory_bytes: 19048
A,B,M=map(int,input().split())
aList=list(map(int,input().split()))
bList=list(map(int,input().split()))
mab=min(aList)+min(bList)
for i in range(M):
  x,y,c=map(int,input().split())
  tt=aList[x-1]+bList[y-1]-c
  if mab > tt:
    mab=tt
print(mab)    
  

Measured memory_bytes: 18736
H, n = map(int, input().split())
A, B = [], []
for _ in range(n):
    a, b = map(int, input().split())
    A.append(a)
    B.append(b)

dp = [1000000000] * (H + max(A) + 1)
dp[0] = 0

for n in range(H+1):
    for a, b in zip(A, B):
        dp[n + a] = min(dp[n + a], dp[n] + b)

print(min(dp[H:]))

Measured memory_bytes: 41708
#include <stdio.h>

int main(void)
{
	int a,b;
	scanf("%d %d",&a, &b);
	if (a > b) {
		printf("a > b\n");
	} else if (a < b) {
		printf("a < b\n");
	} else {
		printf("a == b\n");
	}
	return 0;
}

Measured memory_bytes: 580
#include <iostream>
#include <cmath>
using namespace std;
int main(){
	int a,b,c;
	while(cin >> a >> b >> c){
		int d[10];
		for(int i=0;i<10;i++) d[i] = 0;
		d[a-1]++;
		d[b-1]++;
		d[c-1]++;
		int e = 19-a-b;
		int f = 0;
		int g = 0;
		for(int i=0;i<10;i++){
			if(d[i]==1) continue;
			if(i>e) f++;
			else g++;
		}
		if(f>g) cout << "NO" << endl;
		else cout << "YES" << endl;
	}
}

Measured memory_bytes: 1152