jiahuimbzuai/CoQuIR huggingface dataset:
//  [c]
#include<stdio.h>

int main(){
  int n,i,j,kotae=1,amari,min=1000000001;
  scanf("%d",&n);
  int a[n];
  for(i=0;i<n;i++){
    scanf("%d",&a[i]);
    if(a[i]<min){min=a[i];}
  }
  if(min==1){
    printf("1");
  return 0;
  }
  amari=0;
  for(i=0;i<n;i++){
    amari+=a[i]%min;
  }
  if(amari==0){
    printf("%d",min);
    return 0;
  } 
  for(j=2;j<=min/2;){
    amari=0;
    for(i=0;i<n;i++){
      amari+=a[i]%j;
    }
    if(amari==0){
      for(i=0;i<n;i++){
        a[i]/=j;
      }
      min/=j;
      kotae*=j;
      j=2;
      if(min==1){
        printf("%d",kotae);
        return 0;
      }
    }else{
      if(j==2)j=3; else j+=2;
    }
  }
  printf("%d",kotae);
  return 0;
}
//  [javascript]
'use strict'
function Main(input){
  input=readAsNumArray(input);
  var N=input.shift();
  input=binarySearchSort(input);
  var A=input;
  if(N===1){
    console.log(A[0]);
    return;
  }
  var g=A[0];
  for(let i=0;i<N-1;i++){
    g=GCM(A[i+1],g);
  }
  console.log(g);
} 

function GCM(a,b){
  while(!(a===0||b===0)){
    if(a>b){
      a=a%b;
    }else{
      b=b%a;
    }
  }
  var m=Math.max(a,b)
  return m;
}

function readAsNumArray(input){

var I=[],i=0;

var checkNum=/^-*\d+/;

var checkSpace=/ +|\n+/;

while(input.length>0){

if(input.match(checkNum)!==null){

I[i]=parseInt(input.match(checkNum)[0]);

input=input.replace(checkNum,""); 

i++;

continue;

}

input=input.replace(checkSpace,"");

continue;

} 
return input=I;
}

function binarySearchSort(arr){
  var n=arr.length;
  var newArr=[];
  for(let i=0;i<n;i++){
    var d=0,m=0,u=n-1;
    m=Math.floor((d+u)/2);
    while(!(d>u)){
      if(newArr[m]<arr[i]){
        d=m+1;
      }else{
        u=m-1;
      }
      m=Math.floor((d+u)/2);
    }
    newArr.splice(m+1,0,arr[i]);
  }
  return newArr;
}


Main(require('fs').readFileSync('/dev/stdin','utf8'));
//  [javascript]
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function gcd(a,b){return b?gcd(b,a%b):a;}

console.log(main());
function main(){
  var n = o.a();
  var a = o.l();
  var ans = a[0];
  for(var i = 1; i < n; i++){
    ans = gcd(ans, a[i]);
  }
  return ans;
}
//  [javascript]
function main(input) {
  var n = input[0]-0
  var m = input[1].split(" ");

  var ans = m.sort((a,b)=>a-b);
  while(ans.length>1){
    var newans = [];
    newans.push(ans[0]-0);
    for(var i=1;i<ans.length;i++){
      var tmp = ans[i]%ans[0];
      if(tmp>0) newans.push(tmp);
    }
    ans = newans.sort((a,b)=>a-b);
  }
  console.log(ans[0]);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"))
//  [go]
package main

import (
	"fmt"
	"math/big"
)

func main() {
	n := 0
	_, _ = fmt.Scan(&n)
	var v int64
	for i := 0; i < n; i++ {
		var tmp int64
		_, _ = fmt.Scan(&tmp)
		v = gcd(v, tmp)
	}
	fmt.Println(v)
}

func gcd(m, n int64) int64 {
	if m == 0 {
		return n
	} else if n == 0 {
		return m
	}
	x := new(big.Int)
	y := new(big.Int)
	z := new(big.Int)
	a := new(big.Int).SetUint64(uint64(m))
	b := new(big.Int).SetUint64(uint64(n))
	return z.GCD(x, y, a, b).Int64()
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n, a, g int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a)
		if i == 0 {
			g = a
		} else {
			g = gcd(g, a)
		}
	}
	fmt.Println(g)
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}
//  [go]
package main

import (
	"fmt"
)

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

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := range a {
		fmt.Scan(&a[i])
	}

	ans := 1000000001
	for i := 0; i < len(a)-1; i++ {
		t := gcd(a[i], a[i+1])
		if t < ans {
			ans = t
		}
	}
	fmt.Println(ans)
}
//  [ruby]
lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

N = lines[0][0]
Inf = 10 ** 10

hp = lines[1].sort!
min = hp[0]

for i in 1..35 do
  next_min = Inf
  for j in 1..N do
    rest = hp[j-1] % min
    if rest != 0 then
      hp[j-1] = rest
    end
    if next_min > hp[j-1] then
      next_min = hp[j-1]
    end
  end
  min = next_min
end
    
puts min
//  [ruby]
input = gets.chomp
N = input.to_i
input = gets.chomp
monster_list = input.split(" ").map{|e| e.to_i}

loop {
  monster_list.sort!
  atacker = monster_list.shift
  monster_list.delete_if { |e| e%atacker == 0 }
  if monster_list.size==0
    monster_list << atacker
  end
  monster_list.sort!
  monster_list[0] -= atacker*(monster_list[0]/atacker)
  monster_list.delete_at(0) if monster_list[0] == 0
  monster_list << atacker
  break if monster_list.size==1
}
puts monster_list.first
//  [ruby]
p eval`sed 's/ \\w*/.gcd(&)/g'`
//  [rust]
use std::io::*;
use std::str::FromStr;

//https://qiita.com/tubo28/items/e6076e9040da57368845
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main(){
    let n:usize = read();
    let mut a:Vec<i32> = (0..n).map(|_| read()).collect();

    let mut min = 0;
    while a.len() != 1 {
        a.sort_by(|x,y|y.cmp(x));
        min = a.pop().unwrap();
        a = a.iter().map(|x| x % min).filter(|x| x.is_positive()).collect();
        a.push(min);
    }

    println!("{}",min);

}
//  [rust]
fn gcd(a: usize, b: usize) -> usize {
    if b > a {
        gcd(b, a)
    } else if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

fn solve() {
    let n: usize = read();
    let a: Vec<usize> = (0..n).map(|_| read::<usize>()).collect();
    let mut m = a[0];
    for i in 1..n {
        m = gcd(m, a[i]);
    }
    println!("{}", m);
}

fn main() {
    let stack_size = 104_857_600;
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

// =========
#[allow(unused_imports)]
use std::cmp::{max, min, Reverse};
#[allow(unused_imports)]
use std::collections::{BinaryHeap, HashMap, HashSet};
#[allow(unused_imports)]
use std::process::exit;

#[allow(dead_code)]
const MOD: usize = 1000000007;

fn read<T: std::str::FromStr>() -> T {
    use std::io::Read;
    let stdin = std::io::stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

// =========
//  [rust]
use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn gcd(x: i64, y: i64) -> i64 {
    if y == 0 {
        x
    } else {
        gcd(y, x % y)
    }
}

fn main() {
    let n: usize = read();
    let mut a: Vec<i64> = vec![];
    for _ in 0..n {
        a.push(read());
    }

    let mut ans = a[0];

    for i in 0..a.len() {
        let ai = a[i];
        ans = gcd(ai, ans);
    }
    println!("{}", ans);
}
//  [swift]
func gcd(x: Int,_ y:Int)->Int{return y>0 ?gcd(y,x%y):x};readLine();print(readLine()!.characters.split(" ").map{Int(String($0))!}.reduce(0){gcd($0, $1)})
//  [swift]
func f(x: Int,_ y:Int)->Int{return y>0 ?f(y,x%y):x};readLine();print(readLine()!.characters.split(" ").reduce(0){f($0,Int(String($1))!)})
//  [swift]
func f(x:Int,_ y:Int)->Int{return y>0 ?f(y,x%y):x};readLine();print(readLine()!.characters.split(" ").reduce(0){f($0,Int(String($1))!)})
//  [typescript]
function main(arg) {
  const _a: string[] = arg.split("\n")
  const _n: number = Number(_a[0])
  const _m: string[] = _a[1].split(" ")
  let list: number[] = []

  for (let i = 0; i < _m.length;i++) {
    list.push(Number(_m[i]))
  }

  while (list.length != 1){
    let min: number = list.reduce((a, b) => a < b ? a : b)
    // console.log(min)
    if (min == 1) return console.log(min)

    for (let j = 0; j < list.length; j++) {
      let div: number = list[j] - Math.floor(list[j] / min) * min 
      if (list[j] == min) {
        list[j] = min
      } else if (div > 0){
        list[j] = div
      } else {
        list[j] = min
      }
    }

    list = list.filter(function (x, i, self) {
      return self.indexOf(x) === i;
    });
  }

  return console.log(list[0])
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
let  lines: string[] = [];
const reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});
reader.on('line', function (line: string) {
  lines.push(line);
});
reader.on('close', function() {
  if (lines.length === 0) return;
  let a: number[] = lines[1].split(/\s/).map(i => parseInt(i)).sort((x, y) => x - y);

  while (a.length > 1) {
    let min: number = a.shift();
    let tmp: number[] = a.map(item => item % min);
    a = tmp.filter(item => item !== 0);
    a.push(min);
  }
  console.log(a[0]);
});
//  [typescript]
namespace Coder {
  class Scanner {
    private buffer: string = '';
    private stdinQueue: any = [];

    constructor() {
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on(
        'data',
        (chunk): void => {
          this.buffer += chunk;
          while (this.stdinQueue.length > 0) {
            const i = this.buffer.indexOf('\n');
            if (i < 0) {
              break;
            }
            let line = this.buffer.substr(0, i);
            if (line.endsWith('\r')) {
              line = line.slice(0, -1);
            }
            this.buffer = this.buffer.substr(i + 1);
            this.stdinQueue.shift()(line);
          }
        },
      );
    }
    public getLine(): Promise<string> {
      return new Promise((resolve, reject) => {
        const i = this.buffer.indexOf('\n');
        if (i >= 0 && this.stdinQueue.length == 0) {
          let line = this.buffer.substr(0, i);
          if (line.endsWith('\r')) {
            line = line.slice(0, -1);
          }
          this.buffer = this.buffer.substr(i + 1);
          resolve(line);
        } else {
          this.stdinQueue.push(resolve);
        }
      });
    }

    public close(): void {
      process.stdin.pause();
    }
  }

  async function slove() {
    const sc = new Scanner();
    const N = +(await sc.getLine());
    const A = (await sc.getLine()).split(' ').map((x) => +x);

    while (true) {
      if (A.filter((x) => x > 0).length === 1) {
        break;
      }
      A.sort((a, b) => a - b);
      let min = 10000000000;
      let index = -1;
      for (let i = 0; i < A.length; i++) {
        if (A[i] > 0 && min > A[i]) {
          min = A[i];
          index = i;
        }
      }
      for (let i = index + 1; i < A.length; i++) {
        A[i] = A[i] % min;
      }
    }
    console.log(A.sort((a, b) => b - a)[0]);
    sc.close();
  }

  slove();
}
//  [python]
s=input()
#s = 'BWBWBW'*100000
pos = 0
w_pos = 0
found_pos = 0
cnt = 0

while True:
    pos = s.find('W')
    if pos == -1:
        break
    cnt += (pos+found_pos - w_pos)
    w_pos+=1
    s = s[pos+1:]
    found_pos += (pos+1)
print(cnt)
//  [python]
s = input()

is_all_swappd = False
n_swap = 0
n_white = s.count('W')
for i in range(n_white):
    w_idx = None
    if i == 0:
        w_idx = s.find('W')
    else:
        w_idx = s[last_w_idx + 1:].find('W') + last_w_idx + 1
    n_swap += w_idx - i
    last_w_idx = w_idx

print(n_swap)
//  [python]
import numpy as np
S = input()

idx = []
i = 0
W_flag = False
for s in S:
    if not W_flag:
        if s == "W":
            continue
        elif s == "B":
            W_flag = True
    
    if s == "W" and W_flag:
        idx.append(i)
    i+=1
print(int(np.sum(idx) - ((0+len(idx)-1)*len(idx)/2)))
//  [java]
import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String st = sc.next();
		int num = st.length();
		boolean isBlack[] = new boolean[st.length()];
		for(int i = 0; i < num; i ++) {
			isBlack[i] = st.charAt(i) == 'B';
		}
		ArrayList<Integer> sameColor = new ArrayList<Integer>();
		int tmp = 0;
		boolean tmpIsBlack = true;
		for(int i = 0; i < num; i ++) {
			if(isBlack[i] != tmpIsBlack) {
				sameColor.add(tmp);
				tmp = 0;
				tmpIsBlack = !tmpIsBlack;
			}
			tmp ++;
		}
		sameColor.add(tmp);
		long count = 0;
		while(sameColor.size() >= 2) {
			if(sameColor.size() <= 1) {
				break;
			}
			count += (long) sameColor.get(0) * sameColor.get(1);
			sameColor.remove(1);
			if(sameColor.size() <= 1) {
				break;
			}
			sameColor.set(1, sameColor.get(0) + sameColor.get(1));
			sameColor.remove(0);
		}
		System.out.println(count);
	}
}
//  [java]
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        sc.close();

        String[] str = s.split("");

        Arrays.sort(str, Comparator.reverseOrder());

        long ans = 0;

        for (int i = 0; i < s.length(); i++) {
            if (str[i].equals("B")) {
                ans += i;
            }
        }

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'B') {
                ans -= i;
            }
        }

        System.out.println(ans);
    }
}
//  [java]
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		String[] input = sc.next().split("");
		long res = 0;
		long numB = 0;
		for (String element : input) {
			if (element.equals("W")) {
				res += numB;
			} else {
				numB++;
			}
		}
		System.out.println(res);

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

int main() {
	string s;
	cin >> s;
	ll ans = 0;
	while (s.length()>=2) {
		if (s.at(0) == 'W')s = s.substr(1);
		else break;
	}
	if (s.length() == 1) {
		cout << 0 << endl;
		return 0;
	}
	ll w = 0;
	for (int i = 0; i < s.length(); i++) {
		if (s.at(i) == 'W') {
			ans += i;
			w++;
		}
	}
	ans -= w * (w - 1) / 2;
	cout << ans << endl;
}
//  [cpp]
#include<iostream>
#include<cstring>
using namespace std;
char S[300000];
long ans;
int main(){
  cin >> S;
  ans = 0;
  int k=0;
  for (int i=0;i<strlen(S);i++){
    if (S[i]=='W'){
      ans+=(i-k);
      k++;
    }
  }
  cout << ans << endl;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s; cin >>s;
    int w=0;
    for (auto c: s) if(c=='W'){w++;}

    int left_white = 0, t;
    long long ret = 0;
    for (int i = 0; i < w; i++) {
        t = s.substr(left_white, s.size()).find('W');
        if (t==0) {
            // do nothing
        }
        else {
            // s[left_white] = 'W';
            if (t>0) s[left_white+t] = 'B';
            ret += t;
        }
        left_white++;
    }
    cout << ret << endl;
    return 0;
}
//  [c]
#include<stdio.h>

int main(){
  char S[200000];
  int N=0;
  long ans=0;
  
  while (scanf("%c",&S[N])!=EOF){N++;}
  N--;

  int L=0,R=N;
  while (1)
  {
    if (R>L)
    {
      while (S[L]!='B'&&L<N){L++;}
      while (S[R]!='W'&&R>0){R--;}
      if(R>L){
        ans += R-L;
        L++;
        R--;
      }
    }else{
      break;
    }
  }
  
  printf("%ld",ans);

  return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
  int n,b=0,w=0;
  long long count=0;
  char s[200005];
  scanf("%s",s);
  n=strlen(s);
  for(int i=0;i<n;i++){
    if(s[i]=='W') w++;
  }
    for(int i=n-1;i>=0;i--){
      if(s[i]=='W'){
        count+=i+1-w;
        w--;
        if(w==0) break;
      }
    }
    printf("%lld",count);



  return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
typedef long long ll;

int main(){
  ll n, cnt=0, w=0, p=0;
  char c[200001]={0};
  scanf("%s",c);
  n=strlen(c);
    
  for(int i=0; i<n; i++){
      if( c[i]=='W' ){
        cnt += i-p;
        p++;
      }
  }
  printf("%lld\n",cnt);
  return 0;
}
//  [javascript]
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));

console.log(main());
function main(){
  var s = o.a(1);
  var l = s.length;
  var ans = 0, w = 0;
  for(var i = l-1; i >= 0; i--){
    if(s[i] === "W")w++;
    else ans += w;
  }
  return ans;
}
//  [javascript]
function main(input) {
    const args = input.split(' ');
    const Stones = args[0].toString();

    var count_B = 0;
    var ans = 0;

    for(var i = 0; i < Stones.length - 1; i++) {
        if (Stones.charAt(i) === 'B') {
            count_B++;
        }
        else {
            ans += count_B;
        }
    }

    console.log(ans);

}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function main(input) {
  var lines = input.split('\n');

  var _lines = _slicedToArray(lines, 1),
      S = _lines[0];

  var ws = S.split('B').map(function (chunk) {
    return chunk.length;
  }); // initial 'W's are useless
  // W..BWW..BW...

  var result = 0;

  for (var i = 0; i < ws.length; i++) {
    result += i * ws[i];
  }

  console.log(result);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function splitNum(line) {
  return line.split(/\s+/).map(function (n) {
    return parseInt(n);
  });
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var s string
	fmt.Scan(&s)

	var cnt, ans int
	for i, c := range s {
		if c == 'W' {
			ans += i - cnt
			cnt++
		}
	}
	fmt.Println(ans)
}
//  [go]
package main

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

func main() {
	var wtr = bufio.NewWriter(os.Stdout)
	var S string
	var sum, t int
	fmt.Scan(&S)
	for i := 0; i < len(S); i++ {
		if S[i] == 'B' {
			t++
		}
		if S[i] == 'W' {
			sum += t
		}
	}

	fmt.Fprintln(wtr, sum)
	_ = wtr.Flush()
}
//  [go]
package main

import "fmt"

func main() {
	var s string
	var total, wtotal int
	fmt.Scanf("%s\n", &s)

	for i := 0; i < len(s); i++ {

		if string(s[i]) == "W" {
			total += i - wtotal
			wtotal++
		}
	}
	fmt.Println(total)

}
//  [ruby]
s=gets.split('')
a=[]
count=0
countw=0
s.each do |i|
  count+=1
  if i == 'W' 
    countw+=1
    a<<[count, countw]
  end
end
output=0
a.each do |i|
  output+=(i[0]-i[1])
end
puts output
//  [ruby]
s = gets.chomp.split("")

bs = s.map.with_index { |c, i| i if c == "B" }.compact
tobe = [*(s.count - bs.count)...s.count]

ans = bs.count.times.inject(0) do |r, i|
  r + tobe[i] - bs[i]
end

puts ans
//  [ruby]
s = gets.chomp.split("")
w = 0
ans = 0
for i in 0..s.length - 1
 if s[i] == "W"
   w += 1
 end
end 
bw = []
for i in 0..s.length - 1
 if s[i] == "B"
   bw.push(w)
 else
   w -= 1
 end
end
for i in 0..bw.length - 1
  ans += bw[i]
end

puts ans
//  [rust]
// Your code here!
use std::io::*;
use std::str::FromStr;
 
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char) 
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}
 
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}

fn string_list(input: String) -> Vec<char> {
    let mut normal = vec![];
    for c in input.chars().into_iter(){
        normal.push(c);
    }
    
    return normal
}


fn main () {
    let s:String = read();
    let mut s_list=string_list(s);
    let mut n : usize = s_list.len();
    
    let mut count:usize = 0;
    let mut ans:usize =0;
    
    for i in 0..n {
        if s_list[i]=='W' {
            ans+=i-count;
            count+=1;
        }
    }
    println!("{}",ans);
}
//  [rust]
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let v: Vec<char> = read::<String>().chars().collect();
    let mut cnt = 0i64;
    let mut tmp = 0;
    for i in v {
        if i == 'W' {
            cnt += tmp;
        } else {
            tmp += 1;
        }
    }
    println!("{}", cnt);
}
//  [rust]
#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]
use {
    proconio::{marker::*, *},
    std::{cmp::*, collections::*, mem::*},
};

fn main() {
    input! {
        mut s:Chars,
    }
    let mut ans = 0i64;
    let mut cb = 0i64;
    for i in 0..s.len() {
        if s[i] == 'B' {
            cb += 1;
        } else {
            ans += cb;
        }
    }
    println!("{}", ans);
}
//  [typescript]
s=require('fs').readFileSync('/dev/stdin','utf8').split('')
r=c=0
Array(s.length).fill().map((_,i)=>s[i]=='W'?r+=c:c++)
console.log(r)
//  [python]
import sys
def inpl(): return list(map(int, sys.stdin.readline().split()))
sys.setrecursionlimit(150000)

N, M, X = map(int, sys.stdin.readline().split())
a = []
for i in range(N):
    a.append(inpl())
b = [0] * M
res = float("INF")
def DFS(cost, start, temp):
    global res
    if min(temp) >= X:
        res = min(res, cost)
        return res
    for i in range(start, N):
        c = temp.copy()
        d = [i + j for i, j in zip(c, a[i][1:])]
        DFS(cost + a[i][0], i + 1, d)
    return res

ans = DFS(0,0,b)
if ans != float("INF"):
    print(ans)
else:
    print(-1)
//  [python]
def resolve():
    n, m, x = map(int, input().split())
    A, C = [], []
    for _ in range(n):
        c_a = list(map(int, input().split()))
        c = c_a.pop(0)
        A.append(c_a)
        C.append(c)

    def dfs(N, B, D):
        if N == n:
            if min(B) < x:
                return -1
            else:
                return D
        r = dfs(N + 1, [x + y for (x, y) in zip(B, A[N])], D + C[N])
        l = dfs(N + 1, B, D)
        if l == r == -1:
            return -1
        else:
            if l == -1:
                return r
            elif r == -1:
                return l
            else:
                return min([l, r])

    print(dfs(0, [0 for i in range(m)], 0))
resolve()
//  [python]
from operator import add
n,m,x = map(int,input().split())
matrix = []
sum_list = [0 for i in range(m+1)]
for i in range(n):
    tmp = list(map(int,input().split()))
    matrix.append(tmp)
def tansaku(l,s):
    #一番前の参考書を入れる入れないで再起して、入れる参考書で得られるリストを返す、もうなければ全部が閾値を超えてるかを判断して超えてれば
    if len(l) == 0:
        if min(s[1:]) >= x:
            return s[0]
        else:
            return 10 ** 8
    else:
        tmp1 = tansaku(l[1:],s)
        s = list(map(add,s,l[0]))
        tmp2 = tansaku(l[1:],s)
        return min(tmp1,tmp2)
ans = tansaku(matrix,sum_list)
if ans == 10**8:
    print(-1)
else:
    print(ans)
//  [python]
N, M, X = map(int, input().split())

import numpy as np
import itertools
from collections import defaultdict

l   = list(range(N))
c   = 0
d   = defaultdict(list)
for i in range(1, N+1):
    for j in itertools.combinations(l, i):
        d[c] = list(j)
        c    += 1

Y = np.zeros((N, M+1), dtype=int)

for i in range(N):
    Y[i] = [int(j) for j in input().split()]

res = []
for i in range(c):
    j   = Y[d[i]].sum(0)
    if np.sum(np.r_[j[1:]] >= X) == M:
        res.append(j[0])

if len(res) > 0:
    print(min(res))
else:
    print(-1)
//  [python]
import numpy as np
from itertools import combinations_with_replacement

N,M,X = map(int,input().split())
CA = []
for i in range(N):
  CA.append(list(map(int,input().split())))

OK = True
CA = np.array(CA)
sums = np.sum(CA,axis=0)
for i in range(1,M+1):
  if sums[i] < X:
    OK = False
    break

if OK == False:
  print(-1)
else:
  # As = []
  # for A in combinations_with_replacement(range(0, N), r=M):
  #   As.append(tuple(set(A)))
  # As = list(map(list, set(As)))
  min_ = sums[0]
  hoge = []
  kouho = list(range(1,N+1))
  for i in combinations_with_replacement(kouho, N):
    hoge.append(list(set(i)))
  hoge = list(map(list, set(map(tuple, hoge))))
  for i in hoge:
    mini_CA = []
    for j in i:
      mini_CA.append(CA[j-1])
    mini_CA = np.array(mini_CA)
    OK2 = True
    sums = np.sum(mini_CA,axis=0)
    for k in range(1,M+1):
      if sums[k] < X:
        OK2 = False
        break
    if OK2 == True and sums[0] < min_:
      min_ = sums[0]
  print(min_)
//  [python]
import itertools

p = list(map(int,input().split()))
N = p[0]
M = p[1]
X = p[2]

l = [[int(i) for i in input().split()] for j in range(N)]
l_a = []
k_1 = list(range(1,N+1))
for i in itertools.combinations_with_replacement(k_1, N):
    l_a.append(list(set(i)))
l_a = list(map(list, set(map(tuple, l_a))))
l_v = float('inf')
f_1 = False
for ls in l_a:
    ls = list(set(ls))
    ans = [0] * M
    val = 0
    for a in ls:# a = [1,2]ながさM
        for ix,i in enumerate(l[a-1][1:]):
            ans[ix] += i
        val += l[a-1][0]
    b = [i for i in ans if i >= X]
    if len(b) == len(ans):
        l_v = min(l_v, val)
        f_1 = True
if f_1:
    print(l_v)
else:
    print(-1)
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    static int res = Integer.MAX_VALUE;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str = br.readLine().split(" ");
        int n = Integer.parseInt(str[0]);
        int m = Integer.parseInt(str[1]);
        int x = Integer.parseInt(str[2]);
        int[] nums = new int[m];
        int[][] books = new int[n][m+1];
        for(int i=0; i<n; ++i) {
            str = br.readLine().split(" ");
            //System.out.println(Arrays.toString(str));
            for (int j = 0; j <= m; j++) {
                books[i][j] = Integer.parseInt(str[j]);
            }
        }
        dfs(0,0,nums,books,n,m,x);
        if(res == 2147483647){
            System.out.println(-1);
        }else{
            System.out.println(res);
        }
    }
    public static void dfs(int idx, int cost,int[] nums, int[][] books, int n, int m, int x){
        //System.out.println(idx + " " + cost + " " + Arrays.toString(nums));
        if(idx == n){
            boolean ok = true;
            for(int i=0; i<m; ++i){
                if(nums[i] < x){
                    ok =false;
                    break;
                }
            }
            if(ok){
               //System.out.println(cost);
               res = Math.min(res, cost);
            }
            return;
        }
        cost += books[idx][0];
        for(int i=1; i<=m; ++i){
            nums[i-1] += books[idx][i];
        }
        dfs(idx+1,cost,nums,books,n,m,x);
        cost -= books[idx][0];
        for(int i=1; i<=m; ++i){
            nums[i-1] -= books[idx][i];
        }
        dfs(idx+1,cost,nums,books,n,m,x);
    }
}
//  [java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String[] str = in.readLine().split(" ");
    int n = Integer.parseInt(str[0]);
    int m = Integer.parseInt(str[1]);
    int x = Integer.parseInt(str[2]);
    int[] c = new int[n];
    int[][] a = new int[n][m];
    
    for(int i = 0; i<n; i++) {
      str = in.readLine().split(" ");
      c[i] = Integer.parseInt(str[0]);
      for(int j = 0; j<m; j++) {
        a[i][j] = Integer.parseInt(str[j+1]);
      }
    }
    
    long ans = Long.MAX_VALUE;
    
    loop1: for(int i = 0; i<Math.pow(2,n); i++) {
      boolean ok = true;
      long res = 0;
      loop2: for(int k = 0; k<m; k++) {
        long sum = 0;
        for(int j = 0; j<n; j++) {
          if((1&i >> j) == 1) {
            res += c[j];
            sum += a[j][k];
          }
          //System.out.println(sum);
        }
        if(sum < x) {
          ok = false;
          break loop2;
        }
        //System.out.println();
      }
      //System.out.println(res/m);
      if(ok) {
        ans = Math.min(ans,res/m); 
      }
    }
    
    if(ans == Long.MAX_VALUE) {
      System.out.println(-1);
    } else {
      System.out.println(ans);
    }
  }
}
//  [java]
import java.util.Scanner;

public class Main {
    static Scanner stdIn = new Scanner(System.in);
    public static void main(String[] args){
        int n = stdIn.nextInt();
        int m = stdIn.nextInt();
        int x = stdIn.nextInt();

        int[] c = new int[n];
        int[][] a = new int[n][m];

        for(int i=0; i<n; i++){
            c[i] = stdIn.nextInt();
            for(int j=0; j<m; j++){
                a[i][j] = stdIn.nextInt();
            }
        }

        boolean[] bit = new boolean[n+1];

        int minCost = Integer.MAX_VALUE;
        while(!bit[n]){
            int sumCost = 0;
            int[] skills = new int[m];
            for(int i=0; i<n; i++){
                if(bit[i]){
                    for(int j=0; j<m; j++){
                        skills[j] += a[i][j];
                    }
                    sumCost += c[i];
                }
            }

            if(clear(skills, x)){
                if(sumCost < minCost){
                    minCost = sumCost;
                }
            }

            setNextBit(bit);
        }

        if(minCost < Integer.MAX_VALUE){
            System.out.println(minCost);
        }else{
            System.out.println(-1);
        }
    }

    static boolean clear(int[] skills, int x){
        for(int i=0; i<skills.length; i++){
            if(skills[i] < x){
                return false;
            }
        }
        return true;
    }

    static void setNextBit(boolean[] bit){
        for(int i=0; i<bit.length; i++){
            bit[i] = (bit[i]) ? false : true;
            if(bit[i]){
                return;
            }
        }
    }
}
//  [java]
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[] c = new int[n];
        int[][] a = new int[n][m];
        for (int i = 0; i < n; i++) {
            c[i] = sc.nextInt();
            for (int j = 0; j < m; j++) {
                a[i][j] = sc.nextInt();
            }
        }
        int[][] dp = new int[1<<n + 1][1<<m +1];
        for (int i = 0; i < n; i++) {
            Arrays.fill(dp[i], Integer.MAX_VALUE);
        }
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i <= 1<<n; i++) {
            int[] sum = new int[m];
            int b = 0;
            for (int j = 0; j < n; j++) {
                if((i>>j & 1) == 1){
                    b += c[j];
                    for (int k = 0; k < m; k++) {
                        sum[k] += a[j][k];
                    }
                }
            }
            boolean ok = true;
            for (int j = 0; j < m; j++) {
                if(sum[j] < x){
                    ok = false;
                    break;
                }
            }
            if(ok){
                ans = Math.min(ans, b);
            }
        }
        if(ans == Integer.MAX_VALUE) ans = -1;
        System.out.println(ans);
        sc.close();

    }

}
//  [java]
import java.util.*;
import javax.lang.model.util.ElementScanner6;
import java.lang.Math;

public class Main {

    public static void main(final String[] args) {
        final Scanner sc = new Scanner(System.in);

        // 入力
        int n = sc.nextInt();
        int m = sc.nextInt();
        int x = sc.nextInt();
        //String s = sc.next();

        // 処理
        int[] c = new int[n];
        int[][] a = new int[n][m];

        for(int i = 0; i < n; i++){
            c[i] = sc.nextInt();
            for(int j = 0; j < m; j++){
                a[i][j] = sc.nextInt();
            }
        }

        int out = 0;

        //不可能チェック
        boolean check = true;
        for(int i = 0; i < m; i++){
            int tmp = 0;
            for(int j = 0; j < n; j++){
                tmp += a[j][i];
            }
            if(tmp < x){
                check = false;
                break; 
            }
        }
        if(check == false){
            out = -1;
        } else {
            //最小金額の初期値
            int min = 0;
            for(int i = 0; i < n; i++){
                min += c[i];
            }

            //全組み合わせ
            int ptn = (int)Math.pow(2, n);
            for(int i = 0; i < ptn; i++){
                int kingaku = 0;
                int[] score = new int[m];
                for(int j = 0; j < n; j++){
                    if(((i)&((int)Math.pow(2,j))) != 0){
                        kingaku += c[j];
                        for(int k = 0; k < m; k++){
                            score[k] += a[j][k];
                        }
                    }
                }
                //scoreチェック
                boolean scheck = true;
                for(int l = 0; l < m; l++){
                    if(score[l] < x){
                        scheck = false;
                        break;
                    }
                }
                if(scheck == true){
                    if(kingaku < min) {
                        min = kingaku;
                    }
                }
            }
            out = min;
        }

        // 出力
        System.out.println(out);
    }
}
//  [cpp]
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int INF = 0x3f3f3f3f;
const int MAXN = 15;
int a[MAXN][MAXN];
int b[MAXN];

int main() {
    int n, m, x;
    scanf("%d%d%d", &n, &m, &x);// don't forget &
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            scanf("%d", &a[i][j]);// don't forget &
        }
    }
    int ans = INF;
    for (int i = 0; i < (1 << n); i++) {
        memset(b, 0, sizeof b);
        int cur = 0;
        for (int j = 0; j < n; j++) {
            if ((i >> j) & 1) {
                cur += a[j + 1][0];
                for (int k = 1; k <= m; k++) {
                    b[k] += a[j + 1][k];
                }
            }
        }
        for (int j = 1; j <= m; j++) {
            if (b[j] < x) {
                cur = INF;
                break;
            }
        }
        ans = min(ans, cur);
    }
    printf("%d", ans == INF ? -1 : ans);
    
    return 0;
}
//  [cpp]
#include<cstdio>
#include<algorithm>
#include<functional>
#define MM 2000000000
void func(int,int);
int n,m,x,c[12],a[12][12],wk[12],mn;
using namespace std;
int main(void)
{
	int i,j;
	scanf("%d %d %d",&n,&m,&x);
	for(i=0;i<n;i++)	{
		scanf("%d",&c[i]);
		for(j=0;j<m;j++)	{
			scanf("%d",&a[i][j]);
		}
	}
	mn=MM;
	for(i=0;i<m;i++)	wk[i]=0;
	func(0,0);
	if(mn!=MM)	printf("%d\n",mn);
	else printf("-1\n");
	return 0;
}
void func(int nn,int sum)
{
	int i,flg;
	if(nn==n)	{
		flg=1;
		for(i=0;i<m;i++)	{
			if(wk[i]<x)	{
				flg=0;	break;
			}
		}
		if(flg==1)	mn=min(mn,sum);
	}
	else {
		func(nn+1,sum);
		for(i=0;i<m;i++)	{
			wk[i]+=a[nn][i];
		}
		func(nn+1,sum+c[nn]);
		for(i=0;i<m;i++)	{
			wk[i]-=a[nn][i];
		}
	}
}
//  [cpp]
#include <stdio.h>
int ans = 1234567890;
int check[20];
int S = 0;
int a,b,c;
int x[20],y[20][20];
void func(int k)
{
	if(k>a)
	{
		for(int j=1;j<=b;j++) if(check[j]<c) return;
		ans = ans<S?ans:S;
		return;
	}
	func(k+1);
	S += x[k];
	for(int j=1;j<=b;j++) check[j] += y[k][j];
	func(k+1);
	for(int j=1;j<=b;j++) check[j] -= y[k][j];
	S -= x[k];
}

int main()
{
	scanf("%d%d%d",&a,&b,&c);
	for(int i=1;i<=a;i++)
	{
		scanf("%d",&x[i]);
		for(int j=1;j<=b;j++) scanf("%d",&y[i][j]);
	}
	func(1);
	printf("%d",ans==1234567890?-1:ans);
}
//  [cpp]
#include <bits/stdc++.h>
#include <cmath>

using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<string> vs;
using pll = pair<ll, ll>;
using vl = vector<ll>;
using vll = vector<vl>;
using vpll = vector<pll>;
struct Edge {
	ll to;
 	ll cost;
 };
using Graph = vector<vector<Edge>>;

#define FOR(i, a, b) for (ll i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)
#define ALL(a) (a).begin(), (a).end()
/***** define constant start *******/
const ll MOD = 1000000007;
const double PI = 3.1415926535897932;
const ll INF = LLONG_MAX;
string abc = "abcdefghijklmnopqrstuvwxyz";
string ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const ll MAX = 10000000;
/****** define constant end ********/
/****** define variable start ******/
ll n, m, x;
vl c;
/******* define variable end *******/
int solve() {
	cin >> n >> m >> x;
	c.resize(n);
	vector<vector<ll>> a(n, vector<ll>(m));
	REP(i, n){
		cin >> c[i];
		REP(j, m){
			cin >> a[i][j];
		}
	}
	ll kane = INF;
	bool flag = false;
	for(ll i = 0; i < 1 << n; ++i){
		ll tmp = i;
		vector<vector<ll>> joutai(1 << n, vector<ll>(n));
		for(ll j = 0; j < n; ++j){
			joutai[i][j] = tmp % 2;
			tmp /= 2;
		}
		vl rikai(m);
		ll kanetmp = 0;
		REP(j, n){
			if(joutai[i][j] == 1){
				kanetmp += c[j];
				REP(k, m){
					rikai[k] += a[j][k];
				}
			}
			ll count = 0;
			REP(k, m){
				if(rikai[k] >= x){
					count++;
				}
			}
			if(count == m){
				flag = true;
				if(kanetmp < kane){
					kane = kanetmp;
				}
			}
		}
	}
	if(flag){
		cout << kane << endl;
	}else{
		cout << -1 << endl;
	}
	return 0;
}

int main() {
	//clock_t start = clock();
	cout << std::fixed << std::setprecision(10);
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int end_solve = solve();
	/*
	clock_t end = clock();
	const double time = static_cast<double>(end - start) / CLOCKS_PER_SEC *
	1000.0; printf("time %lf[ms]\n", time);
	*/

	return end_solve;
}
//  [cpp]
#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
//#include <vector>
using namespace std;

int main(){
  int N,M,X;cin>>N>>M>>X;
  vector<int> C(N);
 // vector<int,vector<int>> A(N,vector<int>(M));
  int A[N][M];
  for(int i=0;i<N;i++){
    cin>>C.at(i);
    for(int j=0;j<M;j++) cin>>A[i][j];
  }
  priority_queue<int,vector<int>,greater<int>> ans;
  
  
  for(int bit=0;bit<(1<<N);bit++){
    vector<int> S;
    for (int i = 0; i < N; ++i) {
      if(bit & (1<<i)){// 列挙に i が含まれるか
        S.push_back(i);
      }
    }
    int sum=0;
    int size=S.size();
    vector<int> unstM(M,0);
    for(int i=0;i<size;i++){
      sum +=C.at(S.at(i));
      //for(int j=0;j<M;j++) unstM.at(j)+=A.at(S.at(i)).at(j);
      for(int j=0;j<M;j++) unstM.at(j)+=A[S.at(i)][j];
    }
    bool can=true;
    for(int i=0;i<M;i++){
      if(unstM.at(i)<X){
        can=false;
        //bool can=false;
        break;
      }
    }
    if(can) ans.push(sum);
  }
  if(ans.empty()) cout<<-1<<endl;
  else cout<<ans.top()<<endl;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std::literals;
using namespace std;

namespace xmaho
{
inline namespace input
{
template<typename T>
T get_value(std::istream& is = std::cin);
template<typename C>
C get_container(std::istream& is = std::cin, typename C::size_type length = std::numeric_limits<typename C::size_type>::max());
}
}
using namespace xmaho;

struct book
{
  unsigned long long price;
  std::vector<unsigned long long> exp;
};

int main()
{
  unsigned long long N, M, X;
  cin >> N >> M >> X;
  std::vector<book> books(N);
  for (auto& e : books) {
    e.exp.resize(M);
    cin >> e.price;
    for (auto& m : e.exp) {
      cin >> m;
    }
  }

  auto ans {numeric_limits<unsigned long long>::max()};
  std::vector<unsigned long long> sum(M); // cache
  for (auto i {1ull}; i < (1 << N); ++i) {
    std::cerr << "i: " << i << '\n';
    for (auto& e : sum) e = 0; // init
    unsigned long long sum_cost {0};
    for (auto j {0ull}; j < N; ++j) {
      if (i & (1 << j)) {
        std::cerr << "i, j: " << i << ' ' << j << '\n';
        sum_cost += books[j].price;
        for (auto k {0ull}; k < M; ++k) {
          sum[k] += books[j].exp[k];
        }
      }
    }
    std::cerr << "sum:";
    for (auto e : sum) std::cerr << ' ' << e;
    std::cerr.put(' ');
    std::cerr << "sum_min: " << *min_element(sum.begin(), sum.end()) << endl;
    if (*min_element(sum.begin(), sum.end()) >= X) {
      ans = min(ans, sum_cost);
    }
  }

  if (ans == numeric_limits<unsigned long long>::max()) {
    cout << -1 << '\n';
    return 0;
  }
  cout << ans << '\n';

  return 0;
}

class initalization
{
  class custom_numpunct: public std::numpunct<char>
  {
  public:
    using numpunct::numpunct;
  protected:
    std::string do_truename() const override { return "Yes"; }
    std::string do_falsename() const override { return "No"; }
  };

public:
  initalization()
  {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.imbue(std::locale(std::cout.getloc(), new custom_numpunct{}));
    std::cout << std::boolalpha << std::fixed << std::setprecision(15);
  }
} initalize;

template<typename T>
T xmaho::input::get_value(std::istream& is)
{ T v {}; is >> v; return v; }

template<typename C>
C xmaho::input::get_container(std::istream& is, typename C::size_type length)
{
  C v {};
  if (length != std::numeric_limits<typename C::size_type>::max())
    v.reserve(length);
  typename C::value_type e {};
  for (auto i {length}; i != 0 && is >> e; --i)
    v.push_back(std::move_if_noexcept(e));
  return v;
}
//  [c]
#include <stdio.h>

int main()
{
  int N, M, X, C[13], A[13][13];
  int sum = 0;
  int j = 0;
  int sum_under = 0;
  int count = 0;
  int sum_end = 200000000;

  scanf("%d", &N);
  scanf("%d", &M);
  scanf("%d", &X);

  for(int i = 0; i < 13; i++){
    C[i] = 0;
    for(int k = 0; k < 13; k++){
      A[i][k] = 0;
    }
  }


  for(int k = 0; k < N; k++){
    scanf("%d", &C[k]);
    for(int i = 0; i < M; i++){
      scanf("%d", &A[k][i]);
    }
  }

  int q, w, e, r, t, y, u, o, p, a, s, d;

  for(q = 0; q < 2; q++){
    for(w = 0; w < 2; w++){
      for(e = 0; e < 2; e++){
        for(r = 0; r < 2; r++){
          for(t = 0; t < 2; t++){
            for(y = 0; y < 2; y++){
              for(u = 0; u < 2; u++){
                for(o = 0; o < 2; o++){
                  for(p = 0; p < 2; p++){
                    for(a = 0; a < 2; a++){
                      for(s = 0; s < 2; s++){
                        for(d = 0; d < 2; d++){
                          sum = q*C[0] + w*C[1] + e*C[2] + r*C[3] + t*C[4] + y*C[5] + u*C[6] + o*C[7] + p*C[8] + a*C[9] + s*C[10] + d*C[11];
                          for(int i = 0; i < M; i++){
                            sum_under = q*A[0][i] + w*A[1][i] + e*A[2][i] + r*A[3][i] + t*A[4][i] + y*A[5][i] + u*A[6][i] + o*A[7][i] + p*A[8][i] + a*A[9][i] + s*A[10][i] + d*A[11][i];
                            if(sum_under >= X){
                              count += 1;
                            }
                          }
                          if(count == M){
                            j = 1;
                            if(sum_end > sum){
                              sum_end = sum;
                            }
                          }
                          count = 0;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

if(j == 1){
  printf("%d\n", sum_end);
}
else{
  printf("-1\n");
}


    return 0;
  }
//  [c]
#include <stdio.h>
#define rep(i,n)for(int i=0;i<(int)(n);i++)
int main(){
    int n,m,x,c[12]={0},a[12][12]={0},y,z[12],b,d=2e9;
    scanf("%d%d%d",&n,&m,&x);
    rep(i,n){
    scanf("%d",&c[i]);
        rep(j,m){
            scanf("%d",&a[i][j]);
        }
    }
    rep(i,2){rep(j,2){rep(k,2){rep(l,2){rep(o,2){rep(p,2){rep(q,2){rep(r,2){rep(s,2){rep(t,2){rep(u,2){rep(v,2){
        y=i*c[0]+j*c[1]+k*c[2]+l*c[3]+o*c[4]+p*c[5]+q*c[6]+r*c[7]+s*c[8]+t*c[9]+u*c[10]+v*c[11];
        for(b=0;b<m;b++){
            z[b]=i*a[0][b]+j*a[1][b]+k*a[2][b]+l*a[3][b]+o*a[4][b]+p*a[5][b]+q*a[6][b]+r*a[7][b]+s*a[8][b]+t*a[9][b]+u*a[10][b]+v*a[11][b];
            if(z[b]<x)break;
        }
        if(b==m&&y<d)d = y;
    }}}}}}}}}}}}
    if(d==(int)2e9)puts("-1");
    else printf("%d",d);
    return 0;
}