Problem: Time Limit: 8 sec / Memory Limit: 64 MB





Example

Input

3 3 2
1 1
2 1 1
3 1 1 1


Output

8

Solution (in CPP):

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

const int INF = 1<<28;
const int MAXN = 10001;
const int MAXK = 15;
int n, m, W, K;
int B[MAXN], weight[MAXN], sum[1<<MAXK], dp[1<<MAXK];

int main() {
  while(cin >> n >> m >> W) {
    --m;
    K = 0;
    int top = 0;
    for(int i = 0; i < n; ++i) {
      int k; cin >> k;
      if(k) top = i;
      for(int j = 0; j < k; ++j) {
        int w; cin >> w;
        if(i) {
          B[i] |= 1 << K;
          weight[K++] = w;
        }
      }
    }

    if(K == 0) {
      cout << 0 << endl;
      continue;
    }

    for(int i = 0; i < (1<<K); ++i) {
      sum[i] = 0;
      for(int j = 0; j < K; ++j) {
        if(i >> j & 1) sum[i] += weight[j];
      }
    }

    fill(dp, dp+(1<<MAXK), INF);
    dp[0] = 0;
    for(int i = 1; i < (1<<K); ++i) {
      for(int j = i; j > 0; j = j - 1 & i) {
        if(sum[j] <= W) dp[i] = min(dp[i], dp[i-j] + 1);
      }
    }

    int res = abs(m - top);
    for(int i = top, j = 0; i > 0; --i) {
      j |= B[i];
      res += dp[j] * 2 - 1;
    }
    cout << res << endl;
  }
  return 0;
}