jiahuimbzuai/CoQuIR huggingface dataset:
//  [c]
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 内部定数
#define D_ARG_MAX		15										// 最大アルゴリズム数
#define D_BOOK_MAX		15										// 最大本数

// 内部構造体 - アルゴリズム情報
typedef struct Arg {
	int mi1Val[D_ARG_MAX];										// 値
} Arg;

// 内部構造体 - 本情報
typedef struct Book {
	int miVal;													// 価格
	Arg mzArg;													// アルゴリズム
} Book;

// 内部変数
static FILE *szpFpI;											// 入力
static Book sz1Book[D_BOOK_MAX];								// 本
static int siBCnt;												// 本数
static int siACnt;												// アルゴリズム数
static int siNVal;												// 必要値

// 内部変数 - テスト用
#ifdef D_TEST
	static int siRes;
	static FILE *szpFpA;
	static int siTNo;
#endif

// １行出力
int
fOutLine(
	char *pcpLine				// <I> １行
)
{
	char lc1Buf[1024];

#ifdef D_TEST
	lc1Buf[0] = '\0';
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, pcpLine)) {
		siRes = -1;
	}
#else
	printf("%s", pcpLine);
#endif

	return 0;
}

// 最小値 - 取得
int
fGetMinI(
	int piVal1					// <I> 値１
	, int piVal2				// <I> 値２
)
{
	if (piVal1 < piVal2) {
		return piVal1;
	}
	else {
		return piVal2;
	}
}

// 金額の最小値 - 取得
int
fGetMin(
	int piBNo					// <I> 本
	, Arg *pzpArg				// <I> アルゴリズム
	, int piSum					// <I> 価格合計
)
{
	int i;

	// 終了
	if (piBNo >= siBCnt) {

		// 必要値チェック
		for (i = 0; i < siACnt; i++) {
			if (pzpArg->mi1Val[i] < siNVal) {
				return INT_MAX;
			}
		}

		return piSum;
	}

	// 買わない
	Arg lzArg;
	memcpy(&lzArg, pzpArg, sizeof(lzArg));
	int liMin = fGetMin(piBNo + 1, &lzArg, piSum);

	// 買う
	for (i = 0; i < siACnt; i++) {
		lzArg.mi1Val[i] += sz1Book[piBNo].mzArg.mi1Val[i];
	}
	int liMin2 = fGetMin(piBNo + 1, &lzArg, piSum + sz1Book[piBNo].miVal);
	liMin = fGetMinI(liMin, liMin2);

	return liMin;
}

// 実行メイン
int
fMain(
)
{
	int i, j;
	char lc1Buf[1024];

	// 本数・アルゴリズム数・必要値 - 取得
	fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
	sscanf(lc1Buf, "%d%d%d", &siBCnt, &siACnt, &siNVal);

	// 本 - 取得
	for (i = 0; i < siBCnt; i++) {
		fscanf(szpFpI, "%d", &sz1Book[i].miVal);
		for (j = 0; j < siACnt; j++) {
			fscanf(szpFpI, "%d", &sz1Book[i].mzArg.mi1Val[j]);
		}
		fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
	}

	// 金額の最小値 - 取得
	Arg lzArg;
	memset(&lzArg, 0, sizeof(lzArg));
	int liMin = fGetMin(0, &lzArg, 0);
	if (liMin == INT_MAX) {
		return -1;
	}

	return liMin;
}

// １回実行
int
fOne(
)
{
	int liRet;
	char lc1Buf[1024];

	// 入力 - セット
#ifdef D_TEST
	sprintf(lc1Buf, ".\\Test\\T%d.txt", siTNo);
	szpFpI = fopen(lc1Buf, "r");
	sprintf(lc1Buf, ".\\Test\\A%d.txt", siTNo);
	szpFpA = fopen(lc1Buf, "r");
	siRes = 0;
#else
	szpFpI = stdin;
#endif

	// 実行メイン
	liRet = fMain();

	// 出力
	sprintf(lc1Buf, "%d\n", liRet);
	fOutLine(lc1Buf);

	// 残データ有無
#ifdef D_TEST
	lc1Buf[0] = '\0';
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, "")) {
		siRes = -1;
	}
#endif

	// テストファイルクローズ
#ifdef D_TEST
	fclose(szpFpI);
	fclose(szpFpA);
#endif

	// テスト結果
#ifdef D_TEST
	if (siRes == 0) {
		printf("OK %d\n", siTNo);
	}
	else {
		printf("NG %d\n", siTNo);
	}
#endif

	return 0;
}

// プログラム開始
int
main()
{

#ifdef D_TEST
	int i;
	for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
		siTNo = i;
		fOne();
	}
#else
	fOne();
#endif

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

#define rep(i, n) for(int i=0; i<(n); ++i)
#define max  100000

//qsort(str, n, sizeof(int), up_comp);
int up_comp(const void *a, const void *b){return *(int*)a - *(int*)b;}
int down_comp(const void *a, const void *b){return *(int*)b - *(int*)a;}
int int_sort( const void * a , const void * b ) {return strcmp(( char * )a , ( char * )b );}
int count_digit(int a){int i=0;while(a!=0){a=a/10;i++;}return i;}
int euclid( int a, int b ){int temp;if(a<b){temp=a;a=b;b=temp;}if(b<1)return -1;if(a%b==0) return b;return euclid(b,a%b);}

int main(void){
 
    int a[13][13];
    int c[13];
    int n, m, x;
    int ans = INT_MAX;
    
    scanf("%d%d%d", &n, &m, &x);
    rep(i, n){
        scanf("%d", &c[i]);
        rep(j, m){
            scanf("%d", &a[i][j]);
        }
    }

    rep(s, 1<<n) {
        int cost = 0;
        int d[max] = {0};
        rep(i, n) {
            if (s>>i&1) {
                cost += c[i];
                rep(j, m){
                    d[j] += a[i][j];
                }
            }
        }

         bool ok = true;
           rep(j, m) {
             if (d[j] < x) {
               ok = false;
               break;
             }
           }
        
        if(ok) ans = fmin(cost, ans);
    }
    
    if (ans == INT_MAX)printf("%d", -1);
    else printf("%d", ans);

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

int N;
int M;
int X;

int check(int **arr, int x)
{
    int *sum;
    int c;
    int d;
    int ans = 1;
    sum = (int *)malloc(sizeof(int) * M);
    for (d = 0; d < M; ++d)
    {
        sum[d] = 0;
        for (c = 0; c < N; ++c)
        {
            sum[d] += abs((x / (int)pow(2, c)) % 2 - 1) * arr[c][d];
        }
        if (sum[d] < X)
        {
            ans *= 0;
        }
    }
    free(sum);
    return ans;
}

int sum(int *C, int x)
{
    int ans = 0;
    int c;
    for (c = 0; c < N; ++c)
    {
        ans += abs((x / (int)pow(2, c)) % 2 - 1) * C[c];
    }
    return ans;
}

int main(void) //code is too dirty
{
    int *C;
    int *a;
    int **A;
    int c;
    int d;
    int temp;
    int x;
    int ans;
    scanf("%d", &N);
    scanf("%d", &M);
    scanf("%d", &X);
    C = (int *)malloc(sizeof(int) * N);
    a = (int *)malloc(sizeof(int) * N * M);
    A = (int **)malloc(sizeof(int *) * N); //sizeof(int*)
    for (c = 0; c < N; ++c)
    {
        A[c] = &a[M * c];
    }
    for (c = 0; c < N; ++c)
    {
        scanf("%d", &C[c]);
        for (d = 0; d < M; ++d)
        {
            scanf("%d", &A[c][d]);
        }
    }
    if (check(A, 0) == 0)
    {
        printf("-1");
        free(C);
        free(a);
        free(A);
        return 0;
    }
    ans = sum(C, 0);
    for (x = 1; x < (int)pow(2, N); ++x)
    {
        if (check(A, x) == 1)
        {
            temp = sum(C, x);
            if (temp < ans)
            {
                ans = temp;
            }
        }
    }
    printf("%d", ans);
    free(C);
    free(a);
    free(A);
    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define Rep(i,a,n)for(int i=(int)(a);i<(int)(n);i++)
#define rep(i,n)Rep(i,0,n)
typedef long long ll;
typedef long double ld;
#define Ma(x,y) ((x)>(y)?(x):(y))
#define mi(x,y) ((x)<(y)?(x):(y))

int main(){
    int n, m, x, c[12] = { 0 }, a[12][12] = { 0 }, y, z[12] = { 0 }, b, d = 1e9, all[12], flag = 0;
    scanf("%d%d%d",&n,&m,&x);
    rep(i,n){
    scanf("%d",&c[i]);
        rep(j,m){
            scanf("%d",&a[i][j]);
        }
    }

    rep(i, 4096) {
        y = 0;
        all[0] = i / 2048;
        Rep(j, 1, 12)all[j] = (i % (int)pow(2,12-j)) / pow(2,11-j);
        rep(j, 12)y += c[j] * all[j];
        for (b = 0; b < m; b++) {
            rep(j, 12)z[b] += all[j]*a[j][b];
            if (z[b] < x)flag++;
            z[b] = 0;
        }
        if (flag==0)d = mi(d, y);
        flag = 0;
    }  
    if (d == (int)1e9)puts("-1");
    else printf("%d", d);
    return 0;
}
//  [javascript]
function calc(index, l, cost, Ai, C, X) {
  const A = Ai[index]
  const c = C[index]
  // console.log('input:', index, A, l, cost)
  cost += c
  let ok = true
  for(let i = 0; i < l.length; i++) {
    l[i] += A[i]
    if (l[i] < X) {
      ok = false
    }
  }
  // それ以下のものを計算

  // console.log('calced', index, A, l, cost, ok)

  if (ok) {
    return cost
  }
  if (index === C.length - 1) {
    return -1
  }

  let min = -1
  for (let i = index + 1; i < C.length; i++) {
    // console.log('recursive', index, i)
    let _min = calc(i, Array.from(l), cost, Ai, C, X)
    if (_min === -1) continue
    if (min === -1) {
      min = _min
    }
    min = min < _min ? min : _min
    // console.log('min:', min)
  }
  return min
}

function main(input) {
  const inputs = input.trim().split('\n')
  let [N, M, X] = inputs[0].split(' ').map(Number)
  let C = []
  let Ai = inputs.slice(1).map(e => {
    const [c, ...ai] = e.split(' ').map(Number)
    C.push(c)
    return ai
  })

  // console.log('log')
  // console.log(N, M, X)
  // console.log(C)
  // console.log(Ai)
  // 総当り 12冊しかないの

  let min = -1

  // すべての本について1冊からM冊まで計算、 最小の値を取得する/
  for(let i = 0; i < N; i++) {
    let _min = calc(i, Array.from(new Array(M)).map(e => 0), 0, Ai, C, X)
    // console.log('root:', _min)
    if (_min === -1) continue
    if (min === -1) {
      min = _min
    }
    min = min < _min ? min : _min
  }
  console.log(min)
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
console.log(function(args){
  const _tmp = args.trim().split('\n');
  const [N,M,X] = _tmp.shift().split(' ').map(v=>0|v);
  const book = [];
  for ( let i = 0; i < N; i++ ) {
    const [price,...A] = _tmp[i].split(' ').map(v=>0|v);
    book.push({price,A});
  }
  let skill = Array(M).fill(0), cheepest = Infinity;
  TEST: for ( let mask = 1; mask < 1 << N; mask++ ) {
    let price = 0;
    skill.fill(0);
    for ( let i = 0; i < N; i++ ) {
      if ( !(mask & 1<<i) ) continue;
      price += book[i].price;
      if ( price >= cheepest ) continue TEST;
      for ( let j = 0; j < M; j++ ) {
        skill[j] += book[i].A[j];
      }
    }
    if ( skill.some(x=>x<X) ) continue;
    cheepest = price;
  }
  return isFinite(cheepest) ? cheepest.toString() : '-1';
}(require('fs').readFileSync('/dev/stdin', 'utf8')));
//  [javascript]
"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(a){return a?cin[cid++]:+cin[cid++];}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(myOut);

function main(){
  var [n,m,x] = nexts(3);
  var a = nextm(n,m+1);
  var ans = 1e9;
  for(var i = 1; i < 1<<n; i++){
    var j = i, t = 0, sum = 0, tot = xArray(0,m);
    while(j){
      if(j & 1){
        sum += a[t][0];
        for(var k = 1; k <= m; k++)tot[k-1] += a[t][k];
      }
      j >>= 1, t++;
    }
    var flag = 1;
    for(var j = 0; j < m; j++)if(tot[j] < x)flag = 0;
    if(flag && ans > sum)ans = sum;
  }
  return ans === 1e9 ? -1 : ans;
}
//  [javascript]
// ABC167 - B
function main(input) {
  var inputs = input.split('\n');
  var line1 = inputs[0].split(' ');
  var n = parseInt(line1[0], 10);
  var m = parseInt(line1[1], 10);
  var x = parseInt(line1[2], 10);

  var c = [];
  var a = [];
  for (var i = 0; i < n; i++) {
    var lineN = inputs[i + 1].split(' ');
    c.push(parseInt(lineN[0], 10));
    a[i] = [];
    for (var j = 1; j < m + 1; j++) {
      a[i].push(parseInt(lineN[j], 10));
    }
  }

  var iniAs = [];
  for (var i = 0; i < m; i++) {
    iniAs.push(0);
  }

  var maxCost = c.reduce((a, b) => a + b) + 1;
  var minCost = maxCost * 1;

  var bits = bitComb(n);
  bits.forEach((bit) => {
    var tempCost = 0;
    var tempAs = iniAs.concat();
    bit.forEach((bitItem) => {
      tempCost += c[bitItem];
      tempAs = sumItems(tempAs.concat(), a[bitItem]);
    });
    if (tempAs.every((foo) => foo >= x)) minCost = Math.min(minCost, tempCost);
  });

  console.log(minCost != maxCost ? minCost : -1);
}

function bitComb(n) {
  var ret = [];
  for (let bit = 0; bit < (1 << n); bit++) {
    let row = [];
    for (let i = 0; i < n; i++) {
      if (bit & (1 << i)) {
        row.push(i);
      }
    }
    ret.push(row);
  }
  return ret;
}

function sumItems(arr1, arr2) {
  var ret = [];
  for (var i = 0; i < arr1.length; i++) {
    ret.push(arr1[i] + arr2[i]);
  }
  return ret;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function main(input) {
  const lines = input.trim().split("\n");
  const [N, M, X] = splitN(lines.shift());

  const costs = [];
  const limit = 2 ** N;
  for (let i = 1; i < limit; i++) {
    const flags = i.toString(2).padStart(N, '0').split('').map(Number);
    const total = {cost: 0, a: []}
    flags.forEach((flg, i) => {
      if (flg) {
        const [c, ...a] = splitN(lines[i]);
        total.cost += c;
        total.a = a.map(
          (v, idx) => v + (total.a[idx] || 0)
        );
      }
    });
    if (total.a.every(v => v >= X)) {
      costs.push(total.cost);
    }
  }

  console.log(costs.length ? Math.min(...costs) : -1);
}


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



function splitN(s) {
  return s.split(' ').map(Number);
}
//  [javascript]
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){  
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
	var one = nextIntArray();
	var N = one[0];
	var M = one[1];
	var X = one[2];
	var list = new Array(N);
	for(var i = 0; i < N; i++){
		var tmp = nextIntArray();
		var cost = tmp[0];
		tmp.shift();
		list[i] = {
			cost : cost,
			rikai : tmp
		};
	}
	var max = 1000000000;
	var output = 1000000000;
	for(var i = 0; i < (1 << N); i++){
		var allRikai = new Array(M).fill(0);
		var isOK = true;
		var cost = 0;
		for(var j = 0; j < N; j++){
			if((i & (1 << j)) != 0){
				cost += list[j].cost;
				for(var k = 0; k < M; k++){
					allRikai[k] += list[j].rikai[k];
				}
			//ここにbitが一致したときの処理入れる
			}
		}
		for(var j = 0; j < M; j++){
			if(allRikai[j] < X){
				isOK = false;
			}
		}
		if(isOK){
			output = Math.min(output, cost);
		}
	//ある1つのbit探索を終えたらここに処理を入れる
	}
	if(output == max){
		myout(-1);
	}else{
		myout(output);
	}
}
//  [go]
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func readInt() (read int) {
	scanner.Scan()
	read, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	return
}

func main() {
	scanner.Split(bufio.ScanWords)
	n := readInt()
	m := readInt()
	x := readInt()

	CA := make([][]int, n)
	for i := range CA {
		CA[i] = make([]int, m+1)
		for j := 0; j < m+1; j++ {
			CA[i][j] = readInt()
		}
	}

	ans := 0
	for i := 0; i < (1 << uint(n)); i++ {
		price := 0
		learn := make([]int, m)
		for k := 0; k < n; k++ {
			if i>>uint(k)&1 == 0 {
				price += CA[k][0]
				for l := 1; l < m+1; l++ {
					learn[l-1] += CA[k][l]
				}
			}
		}
		update := true
		for _, v := range learn {
			if v < x {
				update = false
			}
		}
		if update && (ans > price || ans == 0) {
			ans = price
		}
	}

	if ans > 0 {
		fmt.Println(ans)
	} else {
		fmt.Println(-1)
	}

}
//  [go]
package main

import (
	"fmt"
)

type Book struct {
	cost int
	values []int
}

func main() {
	var n, m, x int
	// var result int = 0
	fmt.Scanf("%d %d %d", &n, &m, &x)

	books := make([]Book, n)

	for i := 0; i < n; i++ {
		var cost int
		fmt.Scan(&cost)
		values := make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Scan(&values[j])
		}
		books[i] = Book{ cost, values }
	}

	fmt.Printf("%d", backtrack(books, x, m));
}

func countFulfill(expect int, curSkill []int) int {
	count := 0
	for i := 0; i < len(curSkill); i++ {
		if curSkill[i] >= expect {
			count++
		}
	}
	return count
}

func addArray(a []int, b[]int) []int {
	c := make([]int, len(a))
	for i := 0; i < len(a); i++ {
		c[i] = a[i] + b[i]
	}
	return c
}

func backtrack(books []Book, expect int, skillNum int) int {
	return loop(books, expect, make([]int, skillNum), 0)
}

func loop(books []Book, expect int, curSkill []int, curCost int) int {
	// 既に満たしている場合をチェック
	var fullfillNum = countFulfill(expect, curSkill)
	if (fullfillNum == len(curSkill)) {
		return curCost
	}

	// 次の本がない場合
	if len(books) == 0 {
		return -1
	}

	cost1 := loop(books[1:], expect, addArray(curSkill, books[0].values), curCost + books[0].cost)
	cost2 := loop(books[1:], expect, curSkill, curCost);

	if cost1 == -1 {
		return cost2
	} else if cost2 ==  -1 {
		return cost1
	} else {
		if cost1 < cost2 {
			return cost1
		} else {
			return cost2
		}
	}
}
//  [go]
package main

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

var n, m, x int
var a [][]int
var c []int
var ans = math.MaxInt64

func dfs(i, cc int, arr []int) {
	if i == n {
		// fmt.Println(cc, arr)
		for j := range arr {
			if arr[j] < x {
				return
			}
		}
		// fmt.Println("update")
		ans = min(ans, cc)
		return
	}

	dfs(i+1, cc, arr)

	arr2 := make([]int, m)
	copy(arr2, arr)
	for k := range a[i] {
		arr2[k] += a[i][k]
	}
	dfs(i+1, cc+c[i], arr2)
}

func main() {
	n, m, x = readInt(), readInt(), readInt()

	a = make([][]int, n)
	c = make([]int, n)
	for i := range a {
		c[i] = readInt()

		a[i] = make([]int, m)
		for j := range a[i] {
			a[i][j] = readInt()
		}
	}

	dfs(0, 0, make([]int, m))

	if ans == math.MaxInt64 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

// sort ------------------------------------------------------------

type xxx struct {
	x int
}

type sortArray []xxx

func (s sortArray) Len() int           { return len(s) }
func (s sortArray) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s sortArray) Less(i, j int) bool { return s[i].x < s[j].x }

// -----------------------------------------------------------------

var (
	readString func() string
	readBytes  func() []byte
)

func init() {
	log.SetFlags(log.Lshortfile)
	readString, readBytes = newReadString(os.Stdin)
}

func newReadString(ior io.Reader) (func() string, func() []byte) {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+11))
	r.Split(bufio.ScanWords)

	f1 := func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
	f2 := func() []byte {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Bytes()
	}
	return f1, f2
}

func readInt() int {
	return int(readInt64())
}

func readInt64() int64 {
	i, err := strconv.ParseInt(readString(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(readString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func sum(a []int) int {
	var ret int
	for i := range a {
		ret += a[i]
	}
	return ret
}

func sumFloat64(a []float64) float64 {
	var ret float64
	for i := range a {
		ret += a[i]
	}
	return ret
}

func gcd(m, n int) int {
	for m%n != 0 {
		m, n = n, m%n
	}
	return n
}

func lcm(m, n int) int {
	return m / gcd(m, n) * n
}
//  [go]
package main

import (
	"fmt"
	"strconv"

	// Reader
	"bufio"
	"os"
	"strings"
)

func main() {




	l := nextLine()

	nc, _ := strconv.Atoi(l[0])
	mc, _ := strconv.Atoi(l[1])
	dx, _ := strconv.Atoi(l[2])
	
	books := make([][]int, nc)
	for n := 0; n < nc; n++ {
		books[n] = make([]int, mc + 1)

		bl := nextLine()
		c, _ := strconv.Atoi(bl[0])
		books[n][0] = c
		for m := 1; m <= mc; m++ {
			x, _ := strconv.Atoi(bl[m])
			books[n][m] = x
		}
	}

	fmt.Printf("%d\n", exec(books, nc, mc, dx))
}

func exec(books [][]int, nc int, mc int, dx int) int {
	var patterns [][]int
	patterns = append(patterns, make([]int, nc))
	patterns = append(patterns, make([]int, nc))
	patterns[len(patterns) - 1][0] = 1

	for n := 1; n < len(books); n++ {
		tmp := patterns
		for _, p := range(tmp) {
			tp := append([]int{}, p...)
			tp[n] = 1
			patterns = append(patterns, tp)
		}
	}

	minCost := -1
	for _, pattern := range(patterns) {
		ret := checkBooks(pattern, books, mc, dx)
		if ret == -1 {
			continue
		}
		if minCost == -1 || ret < minCost {
			minCost = ret
		}
	}
	return minCost
}


func checkBooks(pattern []int, books [][]int, mc int, dx int) int {
	totals := make([]int, mc + 1)
	for key, book := range(books) {
		if pattern[key] == 0 {
			continue
		}

		for k, v := range(book) {
			totals[k] += v
		}
	}

	for m := 1; m <= mc; m++ {
		if totals[m] < dx {
			return -1
		}
	}

	return totals[0]
}

func remove(books [][]int, search int) [][]int {
    result := [][]int{}
    for k, v := range books {
        if k != search {
            result = append(result, v)
        }
    }
    return result
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}

// Reader
var limit int = 10000000
var rdr = bufio.NewReaderSize(os.Stdin, limit)

func nextLine() []string {
	return parseLine(readLine())
}

func readLine() string {
	buf := make([]byte, 0, limit)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func parseLine(s string) []string {
	slice := strings.Split(s, " ")
	return slice
}
//  [go]
package main

import (
	"fmt"
)

var (
	finv, inv, fac [MAX]int
)

func COM(n, k int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD
}

func init() {
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1
	inv[1] = 1
	for i := 2; i < MAX; i++ {
		fac[i] = fac[i-1] * i % MOD
		inv[i] = MOD - inv[MOD%i]*(MOD/i)%MOD
		finv[i] = finv[i-1] * inv[i] % MOD
	}
}

const (
	MOD = 1000000007
	MAX = 510000
)

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	return a * b % MOD
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	value int
	index int
	A, B  int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *QS) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Q)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func FactoredPrimeNumber(num int) map[int]int {
	m := map[int]int{}
	return factor(m, num, 2)
}

func factor(result map[int]int, num, pnum int) map[int]int {
	if pnum*pnum > num {
		if num != 1 {
			result[num] += 1
		}
		return result
	}

	if num%pnum == 0 {
		num /= pnum
		result[pnum]++
	} else {
		pnum++
	}
	return factor(result, num, pnum)
}

func GCD(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return GCD(b, a%b)
}

func LCM(a, b int64) int64 {
	return a * b / GCD(a, b)
}

func main() {
	var N, M, X int
	fmt.Scanf("%d %d %d\n", &N, &M, &X)

	C := make([]int, N)
	m := [100][]int{}
	for i := 0; i < N; i++ {
		var c int
		fmt.Scan(&c)
		C[i] = c
		for j := 0; j < M; j++ {
			var b int
			fmt.Scan(&b)
			m[i] = append(m[i], b)
		}
	}
	min := int(1e9)
	r := false
	for i := 1; i < 1<<uint(N); i++ {
		sum := make([]int, M)
		coin := 0
		for j := 0; j < N; j++ {
			if i&(1<<uint(j)) > 0 {
				coin += C[j]
				for k := 0; k < M; k++ {
					sum[k] += m[j][k]
				}
			}
		}
		ok := true
		for _, s := range sum {
			if s < X {
				ok = false
				break
			}
		}
		if ok && min > coin {
			r = true
			min = coin
		}
	}
	if r {
		fmt.Println(min)
	} else {
		fmt.Println(-1)
	}
}

func Reverse(runes []rune) []rune {
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return runes
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var (
		bookNum   int
		studyNum  int
		goalLevel int
	)
	fmt.Scan(&bookNum, &studyNum, &goalLevel)

	bookPrices := []int{}
	levels := [][]int{}
	for i := 0; i < bookNum; i++ {
		bookPrice := 0
		fmt.Scan(&bookPrice)
		bookPrices = append(bookPrices, bookPrice)

		bookLevels := []int{}
		for j := 0; j < studyNum; j++ {
			level := 0
			fmt.Scan(&level)
			bookLevels = append(bookLevels, level)
		}
		levels = append(levels, bookLevels)
	}

	okPrices := []int{}
	for bits := 0; bits < (1 << uint64(bookNum)); bits++ {
		sumPrice := 0
		levelsums := make(map[int]int)

		for i := 0; i <= bookNum; i++ {
			if (bits>>uint64(i))&1 == 1 {
				sumPrice += (bookPrices[i])
				for j, v := range levels[i] {
					levelsums[j] = levelsums[j] + v
				}
			}
		}

		okNum := 0
		for _, v := range levelsums {
			if v >= goalLevel {
				okNum++
			}
			if okNum == studyNum {
				okPrices = append(okPrices, sumPrice)
			}
		}
	}

	if len(okPrices) == 0 {
		fmt.Println("-1")
	} else {
		fmt.Println(minInt(okPrices))
	}

}

func minInt(a []int) int {
	sort.Sort(sort.IntSlice(a))
	return a[0]
}
//  [ruby]
def solve(idx, money, current)
  return money if current.all? { |u| u >= X }
  return -1 if idx >= N

  s1 = solve(idx + 1, money, current.dup)
  M.times do |i|
    current[i] += UNDERSTANDINGS[idx][i]
  end
  s2 = solve(idx + 1, money + PRICES[idx], current.dup)

  return s2 if s1 == -1
  return s1 if s2 == -1

  [s1, s2].min
end

N, M, X = gets.split.map(&:to_i)
a = N.times.map { gets.split.map(&:to_i) }
PRICES = []
UNDERSTANDINGS = []
a.each do |a1|
  PRICES << a1[0]
  UNDERSTANDINGS << a1[1..-1]
end

current = Array.new(M, 0)
puts solve(0, 0, current)
//  [ruby]
def solve(idx, end_idx, money, prices, current, understandings, target)
  return money if current.all? { |u| u >= target }
  return -1 if idx >= end_idx

  s1 = solve(idx + 1, end_idx, money, prices, current.dup, understandings, target)
  M.times do |i|
    current[i] += understandings[idx][i]
  end
  s2 = solve(idx + 1, end_idx, money + prices[idx], prices, current.dup, understandings, target)

  if s1 == -1 && s2 == -1
    -1
  elsif s2 == -1
    s1
  elsif s1 == -1
    s2
  else
    [s1, s2].min
  end
end

N, M, X = gets.split.map(&:to_i)
a = N.times.map { gets.split.map(&:to_i) }
prices = []
understandings= []
a.each do |a1|
  prices << a1[0]
  understandings << a1[1..-1]
end

current = Array.new(M, 0)
puts solve(0, N, 0, prices, current, understandings, X)
//  [ruby]
N, M, X = gets.chomp.split(" ").map(&:to_i)
C = []
A = []

N.times do
  c, *a = gets.chomp.split(" ").map(&:to_i)
  C << c
  A << a
end

SUC = []

def rec(i, s, c)
  if s.all? {|n| n >= X } then
    SUC << c
    return
  end
  return if i == N
  rec(i + 1, s, c)
  rec(i + 1, s.zip(A[i]).map {|a,b| a+b}, c + C[i])
end

rec(0, [0] * M, 0)

if SUC.size == 0 then
  puts "-1"
  return
end
puts SUC.min
//  [ruby]
require 'matrix'

n, m, x = gets.split.map(&:to_i)
a = Matrix.zero(n, m + 1)
n.times do |i|
  b = gets.split.map(&:to_i)
  0.upto(m) do |j|
    a[i, j] = b[j]
  end
end
1.upto(m) do |j|
  if (a.column(j).covector * Vector.elements(Array.new(n, 1)))[0] < x
        puts "-1"
    exit
  end
end
min = Float::INFINITY
1.upto(2 ** n - 1) do |bit|
  ans = 0
  sum = 0
  1.upto(m) do |j|
    sum = (a.column(j).covector * Vector.elements(bit.to_s(2).rjust(n, "0").split('').map(&:to_i)))[0]
    break if sum < x
  end
  if sum >= x
    ans = (a.column(0).covector * Vector.elements(bit.to_s(2).rjust(n, "0").split('').map(&:to_i)))[0]
    min = ans if min > ans
  end
end
puts min
//  [ruby]
require 'matrix'

n, m, x = gets.split.map(&:to_i)
a = Matrix.zero(n, m + 1)
n.times do |i|
  b = gets.split.map(&:to_i)
  0.upto(m) do |j|
    a[i, j] = b[j]
  end
end
min = Float::INFINITY
1.upto(2 ** n - 1) do |bit|
  ans = 0
  sum = 0
  v = 0
  1.upto(m) do |j|
    v = Vector.elements(bit.to_s(2).rjust(n, "0").split('').map(&:to_i))
    sum = (a.column(j).covector * v)[0]
    break if sum < x
  end
  if sum >= x
    ans = (a.column(0).covector * v)[0]
    min = ans if min > ans
  end
end
puts (min == Float::INFINITY ? -1 : min)
//  [ruby]
require 'matrix'

n, m, x = gets.split.map(&:to_i)
a = Matrix.zero(n, m + 1)
n.times do |i|
  b = gets.split.map(&:to_i)
  0.upto(m) do |j|
    a[i, j] = b[j]
  end
end
min = Float::INFINITY
[0, 1].repeated_permutation(n) do |bit|
  ans = 0
  sum = 0
  1.upto(m) do |j|
    sum = (a.column(j).covector * Vector.elements(bit))[0]
    break if sum < x
  end
  if sum >= x
    ans = (a.column(0).covector * Vector.elements(bit))[0]
    min = ans if min > ans
  end
end
puts (min == Float::INFINITY ? -1 : min)
//  [rust]
#[allow(unused_imports)]
use proconio::{
    fastout, input,
    marker::{Bytes, Chars, Isize1, Usize1},
};

#[allow(unused_macros)]
macro_rules! echo {
    ($($e:expr),+) => ( { $(println!("{}", $e))+ } );
}

fn dfs(
    idx: usize,
    cs: &Vec<Vec<usize>>,
    mut skills: Vec<usize>,
    c: usize,
    mut c_min: usize,
    n: usize,
    x: usize,
) -> isize {
    if idx >= n {
        if skills.iter().all(|&s| s >= x) {
            c_min = std::cmp::min(c, c_min);
            return c_min.clone() as isize;
        } else {
            return -1;
        }
    }

    let a = dfs(idx + 1, cs, skills.clone(), c, c_min, n, x);

    let c = c + cs[idx][0];
    for (i, s) in skills.iter_mut().enumerate() {
        *s += cs[idx][i + 1];
    }

    let b = dfs(idx + 1, cs, skills.clone(), c, c_min, n, x);

    if a != -1 && b != -1 {
        return std::cmp::min(a, b);
    } else if a == -1 && b == -1 {
        return -1;
    } else {
        // 片方だけ -1
        return std::cmp::max(a, b);
    }
}

fn main() {
    input! {
        n: usize,
        m: usize,
        x: usize,
        cs: [[usize; m + 1]; n],
    }

    let ans = dfs(0, &cs, vec![0; m], 0, std::usize::MAX, n, x);

    echo!(ans);
}
//  [rust]
// -*- coding:utf-8-unix -*-

use std::cmp;
use proconio::input;
// ABC086C - Traveling
// https://atcoder.jp/contests/abs/fasks/arc089_a

fn main() {
/*     input! {
        n: usize,
        mut plan: [(i32, i32, i32); n],  // Vec<(i32, i32, i32)>
    }
 */
    input! {
        n: usize,
        m: usize,
        x: usize,
        cs: [(u32,[usize;m]);n],
    }

    let mut result = u32::max_value();
    for i in 0..(1 << n) { //nの買う買わない全パターンを回す。
        let mut c = 0;
        let mut tot_a = vec![0;m];
        for (j,ca) in cs.iter().enumerate(){
            if (i >> j) & 1 == 1 {
                c += ca.0;
                for (k, a) in ca.1.iter().enumerate(){
                    tot_a[k] += a;
                }
            }
        }
        if tot_a.iter().all(|y| *y >= x ) {
            result = cmp::min(result, c);
        }
    }
    if result == u32::max_value() {
        println!("-1");
    } else {
        println!("{}",result);
    }
}
//  [rust]
use proconio::input;
use std::cmp::min;
fn main() {
    input!{
        n:usize,
        m:usize,
        x:usize,
        text:[[usize;m+1];n]
    }
    let mut ans = 1000000000;
    for bit in 0..(1<<n){
        let mut cost = 0;
        let mut skill = vec![0; m];
        for i in 0..n{
            if (bit>>i) & 1 == 0 {
                continue;
            }
            cost += text[i][0];
            for j in 0..m{
                skill[j] += text[i][j+1];
            }
        }
        let mut flag = true;
        for i in 0..m{
            if skill[i] < x{
                flag = false;
                break;
            }
        }
        if flag {
            ans = min(ans, cost);
        }
    }
    if ans == 1000000000{
        println!("{}", -1);
    }else{
        println!("{}", ans);
    }

}
//  [rust]
#[allow(unused_imports)]
use std::cmp::{max, min};
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet};
#[allow(unused_imports)]
use std::io::*;
#[allow(unused_imports)]
use std::str::*;

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let cin = stdin();
    let cin = cin.lock();
    let s: String = cin
        .bytes() // Bytes
        .map(|c| c.expect("failed reading char") as char)
        .skip_while(|c| c.is_whitespace()) // c が whitespace である限り skip
        .take_while(|c| !c.is_whitespace()) // c が whitespace でない限り要素を返す
        .collect();
    s.parse().ok().expect("failed parsing")
}

#[allow(non_snake_case)]
fn main() {
    input! {
        N:usize,
        M:usize,
        X:usize,
        A:[[usize; M + 1]; N]
    }
    let maxi = 1 << N;
    let mut m = std::usize::MAX;
    for i in 0..maxi {
        let mut v = vec![0; M];
        let mut m2 = 0;
        for k in 0..N {
            if ((i >> k) & 1) == 1 {
                m2 += A[k][0];
                for j in 0..M {
                    v[j] += A[k][j + 1];
                }
            }
        }
        let mut f = true;
        for j in 0..M {
            if v[j] < X {
                f = false;
            }
        }
        dbg!(m2, v);
        if f {
            m = min(m, m2);
        }
    }
    if m == std::usize::MAX {
        println!("-1");
    } else {
        println!("{}", m);
    }
}
//  [swift]
func readArrayInt() -> [Int] {
    readLine()!.split(separator: " ").map({Int($0)!})
}

// input
var line = readArrayInt()
let (N, M, X) = (line[0], line[1], line[2])
var C: [Int] = []
var A: [[Int]] = []
(1...N).forEach({ _ in
    line = readArrayInt()
    C.append(line[0])
    A.append(Array(line[1...M]))
})

// main
func allAchived(_ bits: Int) -> Bool {
    var achieved = Array(repeating: 0, count: M)
    (0..<N).forEach({ place in
        if ((1 << place & bits) > 0) {
            for (i, value) in A[place].enumerated() {
                achieved[i] += value
            }
        }
    })
    return !achieved.contains(where: {$0 < X})
}

func cost(_ bits: Int) -> Int {
    var cost = 0
    for i in 0..<N where ((1 << i & bits) > 0) {
        cost += C[i]
    }
    return cost
}

var ans = -1
(1..<(1 << N)).forEach { bits in
    if (allAchived(bits)) {
        ans = ans < 0 ? cost(bits) : min(cost(bits), ans)
    }
}

print(ans)
//  [swift]
func readArrayInt() -> [Int] {
    readLine()!.split(separator: " ").map({Int($0)!})
}

// input
var line = readArrayInt()
let (N, M, X) = (line[0], line[1], line[2])
var C: [Int] = []
var A: [[Int]] = []
(1...N).forEach({ _ in
    line = readArrayInt()
    C.append(line[0])
    A.append(Array(line[1...M]))
})

// main
func allAchived(_ bits: Int) -> Bool {
    var achieved = Array(repeating: 0, count: M)
    (0..<N).forEach({ place in
        if ((1 << place & bits) > 0) {
            for (i, value) in A[place].enumerated() {
                achieved[i] += value
            }
        }
    })
    for i in 0..<M {
        if (achieved[i] < X) {
            return false
        }
    }
    return true
}

func cost(_ bits: Int) -> Int {
    var cost = 0
    (0..<N).forEach({ place in
        if ((1 << place & bits) > 0) {
            cost += C[place]
        }
    })
    return cost
}

var ans = -1
(1..<(1 << N)).forEach { bits in
    if (allAchived(bits)) {
        ans = ans < 0 ? cost(bits) : min(cost(bits), ans)
    }
}

print(ans)
//  [swift]
func backtrack(_ price: Int, _ points: [Int], _ remained: Int, 
               _ bookIndex: Int, _ prices: [Int], _ bookPoints: [[Int]]) -> Int {
	if remained == 0 {
      return price
    }
  	if bookIndex == prices.count {
    	return Int.max
    }
	
 	let notPick = backtrack(price, points, remained, bookIndex + 1, prices, bookPoints)
  	let nextPrice = price + prices[bookIndex]
  	var remained = remained
  	var points = points
  	for i in 0..<bookPoints[bookIndex].count {
      	let prev = points[i]
  		points[i] -= bookPoints[bookIndex][i]
      	if prev > 0 && points[i] <= 0 {
          remained -= 1
        }
    }
  	let pick = backtrack(nextPrice, points, remained, bookIndex + 1, prices, bookPoints)
  	return min(pick, notPick)
}


let first = readLine()!.split(separator: " ")
let N = Int(first[0])!
let M = Int(first[1])!
let X = Int(first[2])!
var prices: [Int] = .init(repeating: -1, count: N)
var points: [Int] = .init(repeating: X, count: M)
var bookPoints: [[Int]] = .init(repeating: .init(repeating: 0, count: M), count: N)
for i in 0..<N {
  let line = readLine()!.split(separator: " ")
  prices[i] = Int(line[0])!
  for j in 0..<M {
    bookPoints[i][j] = Int(line[j + 1])!
  }
}
let res = backtrack(0, points, M, 0, prices, bookPoints)
print(res == .max ? -1 : res)
//  [swift]
import Foundation

var mintotal = Int.max
var memo: [[Int]: [Int]] = [:]

func calc(indexes: [Int]) -> [Int] {

    if let r = memo[indexes] {
        return r
    }

    var values:[Int] = [Int](repeating: 0, count: M + 1)
    for i in indexes {
        let book = books[i]
        for v in 0..<(M + 1) {
            values[v] += book[v]
        }
    }

    memo[indexes] = values
    return values
}

// indexes: 選ぶ参考書, threshold: 目標の値
func check(indexes: [Int]) {
    var values = calc(indexes:indexes)

    let total = values.first!
    values.removeFirst()
    if values.filter({$0 < X}).count > 0 {
        return
    }

    //print(total)
    mintotal = min(mintotal, total)
}

func search(indexes: [Int], current: inout [Int]) {
    if indexes.isEmpty { return }

    var copyIndexrs = indexes
    let first = copyIndexrs.first!
    copyIndexrs.removeFirst()

    //print("\(first), \(current)")
    check(indexes: current + [first])

    search(indexes: copyIndexrs, current: &current)
    current.append(first)
    search(indexes: copyIndexrs, current: &current)
    current.removeLast()
}

// main...

var values = readLine()!.components(separatedBy: " ")
let N = Int(values[0])! // 参考書の数
let M = Int(values[1])! // アルゴリズムの数
let X = Int(values[2])! // 目標の理解度

var books:[[Int]] = []
for _ in 0..<N {
    let book = readLine()!.components(separatedBy: " ").map{Int($0)!}
    books.append(book)
}

// 全部の組み合わせを検査する
let indexes = Array(0..<N)

var current:[Int] = []
search(indexes: indexes, current: &current)

if mintotal != Int.max {
    print(mintotal)
} else {
    print(-1)
}
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let nmx = readInts()
    let (n, m, x) = (nmx[0], nmx[1], nmx[2])
    /// 金額の配列
    var aryCost = [Int]()
    /// 理解度の多次元配列
    var tableUnst = [[Int]]()
    
    for _ in 0..<n {
        let ca = readInts()
        aryCost.append(ca[0])
        tableUnst.append(Array(ca[1...m]))
    }
    //________________________________________ここまで入力
    
    var ans = Int.max
    // bit全探索で解を求める
    for bit in 0..<(1<<n) {
        var res = 0
        var aryUnst = [Int](repeating: 0, count: m)
        
        for i in 0..<n {
            if bit >> i & 1 == 1 {
                res += aryCost[i]
                
                
                for j in 0..<m {
                    aryUnst[j] += tableUnst[i][j]
                }
            }
        }
        if aryUnst.min()! >= x {
            ans = min(res, ans)
        }
    }
    print(ans == Int.max ? -1: ans)
}
main()
//  [swift]
import Foundation

func check(t: [[Int]], d: [Bool], x: Int) -> Bool {
  var rst = [Int](repeating: 0, count: t[0].count)
  for i in 0..<t.count {
    if !d[i] { continue }
    for j in 0..<t[i].count {
      rst[j] += t[i][j]
    }
  }
  let ans = rst.contains { x > $0 }
  return !ans
}

func calc(c: [Int], d: [Bool]) -> Int {
  return c.enumerated().reduce(0) { (a, e) in
    return d[e.0] ? a + c[e.0] : a
  }
}

if let s = readLine() {
  let ss = s.split(separator: " ").map { Int($0)! }
  let n = ss[0] // 参考書数
  let m = ss[1] // アルゴリズム数
  let x = ss[2] // 目標理解度
  var c = [Int](repeating: 0, count: n)
  var a = [[Int]](repeating: [Int](repeating: 0, count: m), count: n)
  for i in 0..<n {
    if let aa = readLine() {
      let t = aa.split(separator: " ").map { Int($0)! }
      c[i] = t[0]
      for j in 1..<m+1 {
        a[i][j-1] = t[j]
      }
    }
  }
  
  let max: Int = Int(truncating: NSDecimalNumber(decimal: pow(2, n)))
  var ans: [Int] = []
  for i in 0..<max {
    var b = String(i, radix: 2)
    for _ in 0..<n-b.count {
      b = "0" + b
    }
    let d = b.enumerated().map { $1 == "1" }
    if check(t: a, d: d, x: x) {
      ans.append(calc(c: c, d: d))
    }
  }
  
  if let min = ans.min() {
    print(min)
  } else {
    print(-1)
  }
}
//  [typescript]
import * as fs from "fs";

const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const [n, m, x] = input[0].split(" ").map((x: string): number => +x);
const a = [];
for (let i = 0; i < n; i++) {
	a.push(input[i + 1].split(" ").map((x: string): number => +x));
}


let min_cost = Infinity;
for (let b = 1; b < 1 << n; b++) {
	let cost = 0;
	const u = new Array(m).fill(0);
	for (let i = 0; i < n; i++) {
		if ((b & (1 << i)) > 0) {
			for (let ii = 0; ii < m; ii++) {
				u[ii] += a[i][ii + 1];
			}
			cost += a[i][0];
		}
	}
	if (u.every(v => v >= x) && cost < min_cost) {
		min_cost = cost;
	}
}

console.log(min_cost === Infinity ? -1 : min_cost);
//  [typescript]
export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [n, m, x]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const c: number[] = [];
    const a: number[][] = [];
    for (let i = 0; i < n; i++) {
      const t: number[] = tmp.shift().split(" ").map(int => parseInt(int));
      c.push(t[0]);
      const l = [];
      for (let j = 0; j < m; j++) {
        l.push(t[j + 1]);
      }
      a.push(l);
    }
    let minCost = Infinity;
    for (let i = 1, len = Math.pow(2, n) - 1; i <= len; i++) {
      const xlist = [];
      for (let j = 0; j < m; j++) {
        xlist.push(0);
      }
      let cost = 0;
      const d = i.toString(2).split("");
      d.reverse();
      for (let j = 0, lenj = d.length; j < lenj; j++) {
        if (d[j] == "1") {
          for (let k = 0; k < m; k++) {
            xlist[k] += a[j][k];
          }
          cost += c[j];
        }
      }
      if (cost >= minCost) {
        continue;
      }
      let boo = true;
      for (let k = 0; k < m; k++) {
        if (xlist[k] < x) {
          boo = false;
          break;
        }
      }
      if (boo) {
        minCost = cost;
      }
    }
    return `${minCost == Infinity ? -1 : minCost}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
import { count } from 'console';

process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', (chunk) => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const [n, m, x] = inputs[0].split(' ').map(Number);

  // 参考書の金額
  let priceList: number[] = [];
  // 各アルゴリズムの理解度
  let textList: number[][] = [];
  // 理解度x以上となる参考書の組み合わせ
  let knowledgeList: number[][] = [];
  // 最小金額
  let result = -1;

  // 入力値より参考書の金額、理解度を設定
  for (let i = 0; i < n; i++) {
    let list = inputs[i + 1].split(' ').map(Number);
    priceList.push(list[0]);
    textList.push(list.slice(1, m + 1));
  }

  // 理解度x以上となる参考書の組み合わせを取得
  for (let i = 0; i < n; i++) {
    let list = getKnowledgeList(i, n, m, x, [i], new Array(m).fill(0), textList);

    if (list.length > 0) {
      if (knowledgeList.length > 0) {
        for (let j = 0; j < list.length; j++) {
          knowledgeList.push(list[j]);
        }
      } else {
        knowledgeList = list;
      }
    }
  }

  // 参考書の金額の最小値を取得
  for (const knowledge of knowledgeList) {
    let sum = 0;
    for (const price of knowledge) {
      sum += priceList[price];
    }
    if (result === -1 || result > sum) {
      result = sum;
    }
  }

  console.log(result);
}

// 理解度x以上となる参考書の組み合わせを取得
function getKnowledgeList(
  j: number,
  n: number,
  m: number,
  x: number,
  list: number[],
  sumList: number[],
  textList: number[][],
): number[][] {
  let knowledgeList: number[][] = [];

  let tempSumList = new Array(m).fill(0);

  for (let i = 0; i < m; i++) {
    tempSumList[i] = sumList[i] + textList[j][i];
  }

  if (checkUnderstand(tempSumList, x)) {
    return [list];
  }

  for (let i = j + 1; i < n; i++) {
    knowledgeList = knowledgeList.concat(
      getKnowledgeList(i, n, m, x, list.concat([i]), tempSumList, textList),
    );
  }
  return knowledgeList;
}

// 理解度x以上を満たすかどうかチェック
function checkUnderstand(numList: number[], x: number): boolean {
  let check = true;

  for (const num of numList) {
    if (num < x) {
      check = false;
      break;
    }
  }

  return check;
}
//  [typescript]
const 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 () {
  const rule = lines.shift().split(" ").map(Number);
  const bookNum = rule[0];
  const algorithmNum = rule[1];
  const target = rule[2];

  let res = Infinity;

  const bookArrays: any = lines.map((line) => {
    return line.split(" ").map((int) => parseInt(int));
  });

  for (let bit = 0; bit < 1 << bookNum; bit++) {
    let row: any[] = [];
    let num = "";
    let resArray = [];
    resArray = Array(bookNum + 1).fill(0);

    for (let i = 0; i < bookNum; i++) {
      num += bookArrays[i];
      if (bit & (1 << i)) {
        //理解度と値段をプラスする
        for (let j = 1; j < bookNum + 1; j++) {
          resArray[j] += bookArrays[i][j];
        }
        resArray[0] += bookArrays[i][0];
        row.push(i);
      }
    }

    let flag = true;
    for (let k = 1; k < resArray.length; k++) {
      if (resArray[k] < target) {
        flag = false;
        break;
      }
    }

    if (flag && resArray[0] < res) {
      res = resArray[0];
    }
  }
  res === Infinity ? (res = -1) : res;
  console.log(res);
});