Problem:
Problem B:
Book Replacement
The deadline of Prof. Hachioji’s assignment is tomorrow. To complete the task, students have
to copy pages of many reference books in the library.
All the reference books are in a storeroom and only the librarian is allowed to enter it. To obtain
a copy of a reference book’s page, a student should ask the librarian to make it. The librarian
brings books out of the storeroom and makes page copies according to the requests. The overall
situation is shown in Figure 1.
Students queue up in front of the counter. Only a single book can be requested at a time. If a
student has more requests, the student goes to the end of the queue after the request has been
served.
In the storeroom, there are m desks
D
1
, ... ,
D
m
, and a shelf. They are placed in a line in this
order, from the door to the back of the room. Up to c books can be put on each of the desks. If
a student requests a book, the librarian enters the storeroom and looks for it on
D
1
, ... ,
D
m
in
this order, and then on the shelf. After finding the book, the librarian takes it and gives a copy
of a page to the student.
Then the librarian returns to the storeroom with the requested book, to put it on
D
1
according to the following procedure.
If
D
1
is not full (in other words, the number of books on
D
1
<
c
), the librarian puts the requested book there.
If
D
1
is full, the librarian
temporarily puts the requested book on the non-full desk closest to the entrance or,
     in case all the desks are full, on the shelf,
finds the book on
D
1
that has not been requested for the longest time (i.e. the least recently used book) and takes it,
puts it on the non-full desk (except
D
1
) closest to the entrance or, in case all the desks except
D
1
are full, on the shelf,
takes the requested book from the temporary place,
and finally puts it on
D
1
.
Your task is to write a program which simulates the behaviors of the students and the librarian,
and evaluates the total cost of the overall process. Costs are associated with
accessing
a desk
or the shelf, that is, putting/taking a book on/from it in the description above. The cost of an
access is
i
for desk
D
i
and
m
+ 1 for the shelf. That is, an access to
D
1
, ... ,
D
m
, and the shelf
costs 1, ... ,
m
, and
m
+ 1, respectively. Costs of other actions are ignored.
Initially, no books are put on desks. No new students appear after opening the library.
Input
The input consists of multiple datasets. The end of the input is indicated by a line containing
three zeros separated by a space. It is not a dataset.
The format of each dataset is as follows.
m c n
k
1
b
11
. . .
b
1
k
1
.
      .
      .
k
n
b
n
1
. . .
b
nk
n
Here, all data items are positive integers.
m
is the number of desks not exceeding 10.
c
is the number of books allowed to put on a desk, which does not exceed 30.
n
is the number of
students not exceeding 100.
k
i
is the number of books requested by the
i
-th student, which does
not exceed 50.
b
ij
is the ID numbe
...(truncated)

Submitted solutions:

code_snippet: #include <iostream>
#include <iomanip>
#include <vector>
#include <array>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <tuple>
#include <cmath>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cfloat>
#include <climits>
#include <cassert>
#include <random>
#include <fstream>

int main() {
	while (true) {
		int m, c, n; std::cin >> m >> c >> n; if (n == 0) break;
		std::vector<std::queue<int>> users(n);
		for (auto& u : users) {
			int k; std::cin >> k;
			for (auto i = 0; i < k; ++i) {
				int b; std::cin >> b;
				u.push(b);
			}
		}
		std::vector<int> current_book_position(100, m), recent_access(101, INT_MAX);
		std::set<int> first_desk;
		std::priority_queue<int, std::vector<int>, std::greater<int>> empty_space;
		for (auto i = 0; i <= m; ++i) empty_space.push(i);
		std::vector<int> desk_rest(m + 1, c); desk_rest.back() = INT_MAX;
		int sum_cost = 0;
		std::queue<int> user_in_row; for (auto i = 0; i < n; ++i) user_in_row.push(i);
		for (auto time = 0; !user_in_row.empty(); ++time) {
			const auto top = user_in_row.front(); user_in_row.pop();
			const auto ref = users[top].front(); users[top].pop();
			if (!users[top].empty()) user_in_row.push(top);
			const auto target_pos = current_book_position[ref];
			if (++desk_rest[target_pos] == 1) {
				empty_space.push(target_pos);
			}
			int cost = target_pos + 1;
			if (desk_rest[0] > 0) {
				cost += 1;
				if (--desk_rest[0] == 0) empty_space.pop();
			}
			else {
				const auto temp_area = empty_space.top();
				if (--desk_rest[temp_area] == 0) {
					empty_space.pop();
				}
				const auto most_least_ref = *std::min_element(first_desk.begin(), first_desk.end(), [&recent_access](int a, int b) {return recent_access[a] < recent_access[b]; });
				const auto escape_area = empty_space.top();
				if (--desk_rest[escape_area] == 0) {
					empty_space.pop();
				}
				if (++desk_rest[temp_area] == 1) {
					empty_space.push(temp_area);
				}
				cost += temp_area + 1 + 1 + escape_area + 1 + temp_area + 1 + 1;
				current_book_position[most_least_ref] = escape_area;
				first_desk.erase(most_least_ref);
			}
			current_book_position[ref] = 0;
			first_desk.insert(ref);
			recent_access[ref] = time;
			sum_cost += cost;
		}
		std::cout << sum_cost << '\n';
	}
}
accuracy: 1
time_ms: 10
memory_kb: 3216
final_rank: 17

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

int main() {
    int M, C, N;
    while (cin >> M >> C >> N, M || C || N) {
        vector<deque<int>> vd(M+1);
        for (int i = 1; i <= 100; i++) vd[M].push_back(i);

        queue<queue<int>> vs;
        for (int i = 0; i < N; i++) {
            int k;
            cin >> k;
            queue<int> q;
            for (int j = 0; j < k; j++) {
                int x;
                cin >> x;
                q.push(x);
            }
            vs.push(q);
        }

        int ans = 0;
        while (vs.size()) {
            auto q =  vs.front();
            vs.pop();
            int book = q.front();
            q.pop();
            if (q.size() > 0) vs.push(q);

            for (int i = 0; i <= M; i++) {
                for (int j = 0; j < vd[i].size(); j++) {
                    if (vd[i][j] == book) {
                        ans += i + 1;
                        vd[i].erase(vd[i].begin() + j);
                        break;
                    }
                }
            }

            if (vd[0].size() < C) {
                vd[0].push_back(book);
                ans += 1;
            } else {
                int p1 = -1, p2 = -1;
                for (int i = 1; i <= M; i++) {
                    if (vd[i].size() < C || i == M) {
                        if (p1 < 0) {
                            p1 = i;
                            if (i == M || vd[i].size() + 1 < C) i--;
                        } else if (p2 < 0) {
                            p2 = i;
                        }
                    }
                }

                int rebook = vd[0].front();
                vd[0].pop_front();
                
                vd[p2].push_back(rebook);
                vd[0].push_back(book);

                ans += (p1 + 1) * 2 + 1;
                ans += p2 + 2;
            }
        }

        cout << ans << endl;
    }

  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3184
final_rank: 19

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int,int> P;
signed main(){
  int m,c,n;
  while(cin>>m>>c>>n,m||c||n){
    int k[n];
    int b[111][55];
    for(int i=0;i<n;i++){
      cin>>k[i];
      for(int j=0;j<k[i];j++) cin>>b[i][j];
    }
    list<int> l[m];
    queue<P> q;
    for(int i=0;i<n;i++) q.push(P(i,0));
    int ans=0;
    while(!q.empty()){
      P p=q.front();q.pop();
      int w=p.first,x=p.second;
      int pos=m;
      for(int i=0;i<m;i++){
	auto latte=find(l[i].begin(),l[i].end(),b[w][x]);
	if(latte!=l[i].end()){
	  pos=i;
	  l[i].erase(latte);
	  break;
	}
      }
      ans+=pos+1;
      if((int)l[0].size()<c){
	l[0].push_front(b[w][x]);
	ans+=1;
      }else{
	int tmp=m;
	for(int i=1;i<m;i++){
	  if((int)l[i].size()<c){
	    tmp=i;
	    l[tmp].push_back(b[w][x]);
	    break;
	  }
	}
	ans+=tmp+1;
	//cout<<ans<<endl;
	int le=l[0].back();
	l[0].pop_back();
	ans+=1;
	int pos=m;
	for(int i=1;i<m;i++){
	  if((int)l[i].size()<c){
	    pos=i;
	    l[pos].push_front(le);
	    break;
	  }
	}
	ans+=pos+1;
	//cout<<ans<<endl;
	if(tmp<m) l[tmp].pop_back();
	ans+=tmp+1;
	//cout<<ans<<endl;
	l[0].push_front(b[w][x]);
	ans+=1;
	//cout<<ans<<endl;
      }
      if(x+1<k[w]) q.push(P(w,x+1));
    }
    cout<<ans<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3160
final_rank: 16

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

int M,C,N;

map<int,int> desk[111];
int take(int bk,int &res){  
  for(int i=0;i<M;i++){
    if( desk[i].count(bk) ) {
      res += i+1;
      desk[i].erase(bk);
      return i;
    }
  }
  res += M+1;
  return M;
}
int put(int bk,int cnt,int st,int &res){
  for(int i=st;i<M;i++){
    if( (int)desk[i].size() < C ) {
      res += i+1;
      desk[i][bk] = cnt;
      return i;      
    }
  }
  res += M+1;
  return M;
}

pair<int,int> mink(map<int,int> &mp){
  auto p = make_pair(0,(1<<19));
  for( auto it = mp.begin(); it != mp.end(); it++ ){
    if( p.second > it->second ) p = *it;
  }
  return p;
}

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

  while( cin >> M >> C >> N && (M|C|N) ){

    queue<int> q;
    queue<int> hq[111];


    for(int i=0;i<N;i++){
      int k; cin >> k;
      for(int j=0;j<k;j++){
        int b; cin >> b; hq[i].push(b);
      }
      q.push(i);
    }
    int res = 0;
    int cnt = 0;
    while( !q.empty() ) {
      cnt++;
      int p = q.front(); q.pop();
      if( hq[p].empty() ) continue;
      int bk = hq[p].front(); hq[p].pop();


      take(bk,res);
      int pid = put(bk,cnt,0,res);
      if( pid != 0 ){
        auto dt = mink(desk[0]);
        take( dt.first, res );
        put( dt.first, dt.second, 1, res );

        take( bk,res);
        assert( put(bk, cnt, 0, res) == 0 );
      }
      //cout << cnt << ": " << res << endl;
      q.push( p );
    }
    for(int i=0;i<=M;i++) desk[i].clear();
    cout << res << endl;
  }
}
accuracy: 1
time_ms: 20
memory_kb: 3112
final_rank: 18

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

int M,C,N;
int D[20][111];
int Ds[20];
int used[111];
int pl[111];
int res;
const int MAX = 101;
vector<int> B[111];
void init(){
  memset( D, 0, sizeof( D ) );
  memset( Ds,0,sizeof( Ds ) );
  memset( pl,0,sizeof( pl ) );
  memset(used,0,sizeof(used));
  res = 0;
  used[MAX] = (1<<29);
}

void put(int q,int id){
  Ds[id]++;
  D[id][q] = 1;
  pl[q] = id;
  res += id+1;
}

void take(int q,int id){
  Ds[id]--;
  D[id][q] = 0;
  pl[q] = -1;
  res += id+1;
}
bool pcheck(int id){
  if( id==M ) return true;
  return Ds[id] < C;
}

int main(){
  while( cin >> M >> C >> N && (M||C||N) ){

    init();
    for(int i=0;i<N;i++){
      int k; cin >> k;
      B[i].resize(k);
      for( int &b : B[i] ) {
        cin >> b;
        D[M][b] = 1;
        pl[b] = M;
      }
    }
    vector<int> query;
    for(int j=0;j<=50;j++){
      for(int i=0;i<N;i++){
        if( (int)B[i].size() <= j ) continue;
        query.push_back( B[i][j] );
      }
    }

    int cnt=1;
    res = 0;
    for( int q: query ){
      used[q] = cnt++;
      for(int i=0;i<=M;i++){
        if( pcheck( i ) || i == pl[q] ){
          take( q, pl[q] );
          put( q, i );          
          break;
        }
      }
      if( pl[q] == 0 ) continue;
      int maxid = MAX;
      for(int i=0;i<=100;i++){
        if( D[0][i] )
          if( used[maxid] > used[i] ) maxid = i;        
      }
      for(int i=1;i<=M;i++){
        if( pcheck( i ) ){          
          take( maxid, pl[maxid] );
          put( maxid, i );    
          break;
        }        
      }
      take( q, pl[q] );
      put( q, 0 );
    }
    cout << res << endl;

  }
}
accuracy: 1
time_ms: 10
memory_kb: 3084
final_rank: 14

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

int main(){
  while(1){
    ll m,c,n;
    cin>>m>>c>>n;
    if(!m&&!c&&!n)return 0;

    vector<ll> book[101],D[21];
    
    for(int i=0;i<n;i++){
      int k;
      cin>>k;
      book[i].resize(k);
      for(int j=0;j<k;j++) cin>>book[i][j],D[m].push_back(book[i][j]);
    }

    queue<int> Q;
    for(int i=0;i<100;i++)
      for(int j=0;j<n;j++)
	if((int)book[j].size()>i)Q.push(book[j][i]);
  
    ll d[11],ans=0;
    for(int i=0;i<m;i++)d[i]=c;  
    d[m]=1e9;
    
    while(!Q.empty()){
      ll id=Q.front();Q.pop();
      ll cost=0;

      for(int i=0;i<=m&&!cost;i++)
	for(int j=0;j<(int)D[i].size()&&!cost;j++)
	  if(id==D[i][j])cost=i+1,D[i].erase(D[i].begin()+j);
      
      ans+=cost;
      cost=0;
      if(D[0].size()<d[0]){
	D[0].push_back(id),ans+=1;
	continue;
      }

      int pos=0;
      for(int i=0;i<=m&&!cost;i++)
	if(D[i].size()<d[i])D[i].push_back(id),cost=(i+1)*2+1,pos=i;
      
      ans+=cost;
      cost=0;
      for(int i=0;i<=m&&!cost;i++)
	if(D[i].size()<d[i]){
	  D[i].push_back(D[0][0]);
	  D[0].erase(D[0].begin());
	  cost=i+2;
	}
      ans+=cost;      
      cost=0;
      for(int i=0;i<D[pos].size();i++) if(D[pos][i]==id)D[pos].erase(D[pos].begin()+i);
      D[0].push_back(id);
    }
    cout<<ans<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3088
final_rank: 15

code_snippet: #include <algorithm>
#include <vector>
#include <cfloat>
#include <string>
#include <cmath>
#include <set>
#include <cstdlib>
#include <map>
#include <ctime>
#include <iomanip>
#include <functional>
#include <deque>
#include <iostream>
#include <cstring>
#include <queue>
#include <cstdio>
#include <stack>
#include <climits>
#include <sys/time.h>
#include <cctype>

using namespace std;

typedef long long ll;

int main() {
  while (true) {
    int m, c, n;
    cin >> m >> c >> n;
    if (m == 0 && c == 0 && n == 0) break;

    queue <int> storder;
    queue <int> stdesire[n];
    vector <int> d[m];
    for (int i = 0; i < n; i++) {
      storder.push(i);
      int k;
      cin >> k;
      for (int j = 0; j < k; j++) {
        int ID;
        cin >> ID;
        stdesire[i].push(ID);
      }
    }
    int ans = 0;
    while (!storder.empty()) {
      int p = storder.front(); storder.pop();
      int cost = 0;
      int ID = stdesire[p].front(); stdesire[p].pop();
      bool ok = false;
      // ??¬?????¨??£?????????
      for (int i = 0; i < m; i++) {
        for (int j = 0; j < d[i].size(); j++) {
          if (d[i][j] == ID) {
            ok = true;
            cost += i+1;
            d[i].erase(d[i].begin()+j);
            break;
          }
        }
        if (ok) break;
      }
      if (!ok) {
        cost += m+1;
      }

      // ??¬?????????
      bool shelf = true;
      for (int i = 0; i < m; i++) {
        if (d[i].size() < c) {
          if (i == 0) {
            d[i].push_back(ID);
            cost += 1;
          }else {
            cost += (i+1)*2+1; ok = false;
            for (int j = 1; j < m; j++) {
              int bias = j == i;
              if (d[j].size()+bias < c) {
                int t = d[0][0];
                d[0].erase(d[0].begin());
                d[j].push_back(t); cost += 1+j+1;
                ok = true;
                break;
              }
            }
            if (!ok) {
              int t = d[0][0];
              d[0].erase(d[0].begin());
              cost += 1+m+1;
            }
            d[0].push_back(ID);
          }
          shelf = false;
          break;
        }
      }
      if (shelf) {
        cost += (m+1)*2+1+(m+1)+1;
        d[0].erase(d[0].begin());
        d[0].push_back(ID);
      }
      if (stdesire[p].size()) {
        storder.push(p);
      }

      ans += cost;
    }

    cout << ans << endl;
  }
}
accuracy: 1
time_ms: 10
memory_kb: 1284
final_rank: 5

code_snippet: #pragma  warning (disable:4996)
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
int m, c, n;
int k[102];
int b[102][52];
vector<int> desk[12];//&#27599;&#24352;&#26700;子上放的&#20070;&#32534;号
int amount[12];
int que[5005];//拿&#20070;&#39034;序
int maxk;
int max(int a, int b){
	if (a > b)return a;
	else return b;
}
int main(){
	while (cin >> m >> c >> n){
		if (!m&&!n&&!c) break;
		int i, j,p;
		
		memset(b, 0, sizeof(b));
		memset(desk, 0, sizeof(desk));
		memset(amount, 0, sizeof(amount));
		memset(que, 0, sizeof(que));
		memset(k, 0, sizeof(k));
		maxk = -10;

		for ( i = 1; i <= n; i++){
			cin >> k[i];
			maxk = max(maxk, k[i]);
			for ( j = 1; j <= k[i]; j++)
				cin >> b[i][j];
		}
		

		int ans = 0;
		int num = 0;

		for (j = 1; j <= maxk; j++){
			for (i = 1; i <= n; i++){
				if (b[i][j] != 0)
				{
					que[num++] = b[i][j];
					
				}
			}
		}
		
		int id;
		int mm = 0;
		
		
		while (mm < num){
			id = que[mm];
			int flag = 0;
			//找&#20070;
			/*for (j = 1; j <= m; j++){
				cout << "desk["<<j<<"]:";
				for (i = 0; i < desk[j].size(); i++)
					cout << desk[j][i] << " ";
				cout << endl;
			}*/
				
			for (i = 1; i <= m; i++){
				for (j = 0; j < desk[i].size(); j++){
					if (desk[i][j] == id) {
						flag = 1;
						ans += i;
						//cout << "第"<<mm<<"cinashu"<<i << endl;
						amount[i]--;
						desk[i][j] = 0;//拿走了
						break;
					}
				}
				if (flag)break;
			}
			if (!flag){
				ans += (m + 1); //cout << "第" << mm << "cinashu" << m+1 << endl;
			}

			//放&#20070;
			int temp;
			if (amount[1] < c){
				desk[1].push_back(id);
				ans += 1;
				amount[1]++;
				
			}
			else{
				for (i = 2; i <= m + 1; i++){
					if (amount[i] < c || (i == m + 1))
					{

						temp = i;//&#26242;&#26102;放的位置
						amount[i]++;
						
						break;
					}
				}
				int longestid;//很久没用的&#20070;

				for (i = 0; i < desk[1].size(); i++){
					if (desk[1][i])
					{
						longestid = desk[1][i];
						desk[1][i] = 0;
					
						break;
					}
				}
				desk[1].push_back(id);
				

				int temp2;	
				for (p = temp ; p <= m + 1; p++){
					if (amount[p] < c || p == m + 1){

						temp2 = p;
						desk[p].push_back(longestid);
						amount[p]++;
						break;
					}
				}
				amount[temp]--;
				ans += (2 * temp + temp2 + 2);
				//cout << temp <<" "<< temp2 <<" "<<2 * temp + temp2 + 2<< endl;


			}mm++;
		}
				
		cout << ans << endl;

		
	}return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 1672
final_rank: 20

code_snippet: #include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstring>
#include <queue>
#include <set>
#include <map>
#include <vector>
template <class T>
inline bool rd(T &ret) {
	char c; int sgn;
	if(c=getchar(),c==EOF) return 0;
	while(c!='-'&&(c<'0'||c>'9')) c=getchar();
	sgn=(c=='-')?-1:1;
	ret=(c=='-')?0:(c-'0');
	while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
	ret*=sgn;
	return 1;
}
template <class T>
inline void pt(T x) {
    if (x <0) {
        putchar('-');
        x = -x;
    }
    if(x>9) pt(x/10);
    putchar(x%10+'0');
}
using namespace std;
const int inf = (int)1e8;
const int N = 55;
typedef pair<int, int> pii;

int n, m, c;

deque<int> Q, q[15];
deque<int>::iterator it;
vector<int>G[105];
int id[105];
void input(){
	while(!Q.empty())Q.pop_front();
	for(int i = 1, num, j; i <= n; i++){
		G[i].clear();
		rd(num); while(num--){rd(j); G[i].push_back(j);	}
		reverse(G[i].begin(), G[i].end());
		if(G[i].size())Q.push_back(i);
	}
	for(int i = 1; i <= m; i++) while(!q[i].empty())q[i].pop_front();
	for(int i = 1; i <= 100; i++)id[i] = m+1;
}
int putbook(int book, int from){
	for(int i = from; i <= m; i++){
		if(q[i].size()<c){
			q[i].push_back(book);
			id[book] = i;
			return i;
		}
	}
	id[book] = m+1;
	return m+1;
}
int takebook(int book){
	if(id[book] == m+1)return m+1;
	for(it = q[id[book]].begin(); it != q[id[book]].end(); it++)
		if(*it == book){
			q[id[book]].erase(it); break;
		}
	return id[book];
}
int main() {
	while(~scanf("%d %d %d", &m, &c, &n), n + c+m){
		input();
		int ans = 0;
		while(!Q.empty()){
			int stu = Q.front();	Q.pop_front();
			int book = G[stu][G[stu].size()-1];
			G[stu].erase(G[stu].end()-1, G[stu].end());
			if(G[stu].size()) Q.push_back(stu);
			ans += takebook(book);
			ans += putbook(book, 1);
			if(id[book]!=1){
				int pre = q[1].front();
				q[1].pop_front();
				ans++;
				ans += putbook(pre, 2);
				ans += takebook(book);
				ans += putbook(book, 1);
			}
		}
		pt(ans); puts("");
	}
    return 0;
}

/*

9 9
*#**#**#*
*#**#**#*
*#**#**#*
*#**.**#*
*#*#.#*#*
*$##*##$*
*#*****#*
*.#.#.#.*
*********
3 3
*$*
*#*
*$*


*/
accuracy: 1
time_ms: 10
memory_kb: 1244
final_rank: 2

code_snippet: #define _USE_MATH_DEFINES
#define INF 0x3f3f3f3f

#include <iostream>
#include <cstdio>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cctype>
#include <utility>
#include <assert.h>
  
using namespace std;
  
typedef long long ll;
typedef pair <int,int> P;
typedef pair <double,P> PP;
  
static const double EPS = 1e-8;

int num_of_desks;
int book_limit;
int num_of_students;

int take_book(int id,deque<int> desks[101]){
  for(int desk_i = 0; desk_i < num_of_desks; desk_i++){
    for(int i = 0; i < desks[desk_i].size(); i++){
      if(desks[desk_i][i] == id){
        deque<int> tmp;
        for(int j = 0; j < desks[desk_i].size(); j++){
          if(desks[desk_i][j] == id) continue;
          tmp.push_back(desks[desk_i][j]);
        }
        desks[desk_i] = tmp;
        return desk_i + 1;
      }
    }
  }
  return num_of_desks + 1;
}

int main(){
  while(~scanf("%d %d %d",&num_of_desks,&book_limit,&num_of_students)){
    if(num_of_desks == 0
       && book_limit == 0
       && num_of_students == 0) break;
    vector<int> students[101];
    int max_request = 0;
    for(int student_i = 0; student_i < num_of_students; student_i++){
      int num_of_books_requested;
      scanf("%d",&num_of_books_requested);
      max_request = max(max_request,num_of_books_requested);
      for(int book_i = 0; book_i < num_of_books_requested; book_i++){
        int id;
        scanf("%d",&id);
        students[student_i].push_back(id);
      }
    }
    queue<int> books;
    for(int book_i = 0; book_i < max_request; book_i++){
      for(int student_i = 0; student_i < num_of_students; student_i++){
        if(students[student_i].size() <= book_i) continue;
        books.push(students[student_i][book_i]);
      }
    }

    deque<int> desks[101];

    int score = 0;
    while(!books.empty()){
      int id = books.front();
      books.pop();

      //take from desk/shelf
      score += take_book(id,desks);

      //put 
      if(desks[0].size() < book_limit){
        desks[0].push_back(id);
        score += 1;
      }
      else{
        int tmp_place = -1;
        for(int desk_i = 1; desk_i <= num_of_desks; desk_i++){
          //put book
          if(desk_i == num_of_desks || desks[desk_i].size() < book_limit){
            desks[desk_i].push_back(id);
            tmp_place = desk_i;
            score += desk_i + 1;
            break;
          }
        }

        //take book
        int old = desks[0].front(); 
        desks[0].pop_front();
        score += 1;

        bool same_flag = false;
        for(int desk_i = 1; desk_i <= num_of_desks; desk_i++){
          //put book
          if(desk_i == num_of_desks || desks[desk_i].size() < book_limit){
            if(tmp_place == desk_i){
              desks[desk_i].pop_back();
              same_flag = true;
            }
            desks[desk_i].push_back(old);
            score += desk_i + 1;
            break;
          }

        }

        //take book
        if(!same_flag){
          desks[tmp_place].pop_back();
        }
        score += tmp_place + 1;

        //put book
        desks[0].push_back(id);
        score += 1;
      }
    }
    printf("%d\n",score);
  }
}
accuracy: 1
time_ms: 20
memory_kb: 1360
final_rank: 12

code_snippet: #include <string> 
#include <algorithm> 
#include <cfloat> 
#include <climits> 
#include <cmath> 
#include <complex> 
#include <cstdio> 
#include <cstdlib> 
#include <cstring> 
#include <functional> 
#include <iostream> 
#include <map> 
#include <memory> 
#include <queue> 
#include <set> 
#include <sstream> 
#include <stack> 
#include <utility> 
#include <vector> 

#define EACH(i,c) for(__typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define ALL(x) (x).begin(),(x).end() 
typedef long long ll;
using namespace std; 
const double eps = 1e-10;

int main(){
    for(;;){
        int m, c, n;
        cin >> m >> c >> n;
        if(m == 0 && c == 0 && n == 0) return 0;
        vector<int> idx(n);
        vector<vector<int> > b(n),
                             desk(m, vector<int>(c, -1)),
                             time(m, vector<int>(c, 0));
        for(int i = 0; i < n; ++i){
            int k;
            cin >> k;
            b[i].resize(k);
            for(int j = 0; j < k; ++j) cin >> b[i][j];
        }
        int curr = 0;
        int cost = 0;
        for(;;){
            bool f = false;
            for(int i = 0; i < n; ++i) if(idx[i] < b[i].size()){
                ++curr;
                f = true;
                int j = idx[i]++;
                bool found = false;
                for(int k = 0; k < m; ++k){
                    for(int l = 0; l < c; ++l) if(desk[k][l] == b[i][j]){
                        cost += k+1;
                        desk[k][l] = -1;
                        found = true;
                    }
                    if(found) break;
                }
                if(!found) cost += m+1;
                found = false;
                for(int l = 0; l < c; ++l) if(desk[0][l] < 0){
                    cost += 1;
                    desk[0][l] = b[i][j];
                    time[0][l] = curr;
                    found = true;
                    break;
                }
                if(found) continue;
                int td = -1, di = -1;
                for(int k = 1; k < m; ++k){
                    for(int l = 0; l < c; ++l) if(desk[k][l] < 0){
                        cost += k+1;
                        td = k;
                        di = l;
                        desk[k][l] = b[i][j];
                        found = true;
                        break;
                    }
                    if(found) break;
                }
                if(!found) {
                    td = m;
                    cost += m+1;
                }
                cost += 1;
                int mt = 1000000000, mi = -1;
                for(int l=0;l<c;++l) if(mt > time[0][l]){
                    mt = time[0][l];
                    mi = l;
                }
                found = false;
                for(int k = 1; k < m; ++k){
                    for(int l = 0; l < c; ++l) if(desk[k][l] < 0){
                        cost += k+1;
                        desk[k][l] = desk[0][mi];
                        time[k][l] = time[0][mi];
                        found = true;
                        break;
                    }
                    if(found) break;
                }
                if(!found) cost += m+1;
                if(td < m) desk[td][di] = -1;
                desk[0][mi] = b[i][j];
                time[0][mi] = curr;
                cost += td+1 + 1;
            }
            if(!f) break;
        }
        cout << cost << endl;
    }
}
accuracy: 1
time_ms: 10
memory_kb: 1244
final_rank: 2

code_snippet: #include<stdio.h>
#include<algorithm>
using namespace std;
int at[110];
int use[110];
int last[110];
int req[110][110];
int sr[110];
int lis[11000];
int main(){
	int a,b,c;
	while(scanf("%d%d%d",&a,&b,&c),a){
		int ret=0;
		for(int i=0;i<110;i++)use[i]=0;
		for(int i=0;i<110;i++)at[i]=a+1;
		for(int i=0;i<110;i++)last[i]=0;
		for(int i=0;i<c;i++){
			int d;scanf("%d",&d);
			sr[i]=d;
			for(int j=0;j<d;j++)scanf("%d",&req[i][j]);
		}
		int L=0;
		for(int i=0;i<60;i++){
			for(int j=0;j<c;j++)if(sr[j]>i)lis[L++]=req[j][i];
		}
		int t=0;
		for(int i=0;i<L;i++){
				int e=lis[i];
				ret+=at[e];
				if(at[e]<a+1)use[at[e]]--;
				last[e]=t;
				t++;
				if(use[1]<b){
					use[1]++;ret++;at[e]=1;
				}else{
					for(int i=2;i<=a+1;i++){
						if(i==a+1||use[i]<b){
							use[i]++;at[e]=i;ret+=i;break;
						}
					}
					int f=9999999;
					int v=0;
					for(int i=0;i<110;i++)if(at[i]==1){
						if(f>last[i]){f=last[i];v=i;}
					}
					ret++;
					for(int i=2;i<=a+1;i++){
						if(i==a+1||use[i]<b){
							use[i]++;at[v]=i;ret+=i;break;
						}
					}
					use[at[e]]--;ret+=at[e];ret++;at[e]=1;
				}
			
		}
		printf("%d\n",ret);
	}
}
accuracy: 1
time_ms: 10
memory_kb: 1104
final_rank: 1

code_snippet: #include <climits>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
 
int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);

	for(int m, c, n; cin >> m >> c >> n && m;) {
		vector<unordered_map<int, int>> desks(m);
 
		queue<int> que;
		vector<int> index(n, 0);
		vector<vector<int>> books(n);
 
		for(int i = 0; i < n; ++i) {
			que.push(i);
 
			int k;
			cin >> k;

			books[i].reserve(k);
 
			for(int j = 0; j < k; ++j) {
				int b;
				cin >> b;
				books[i].emplace_back(b);
			}
		}
 
		int ans = 0;

		for(int t = 0; !que.empty(); ++t) {
			const int student = que.front();
			que.pop();
 
			const int id = books[student][index[student]];
			if(++index[student] < books[student].size()) {
				que.push(student);
			}

			int pos = m;
			for(int i = 0; i < m; ++i) {
				if(desks[i].count(id)) {
					desks[i].erase(id);
					pos = i;
					break;
				}
			}
 
			ans += pos + 1;
 
			int tmp = m;
			for(int i = 0; i < m; ++i) {
				if(desks[i].size() < c) {
					desks[i].insert({id, t});
					tmp = i;
					break;
				}
			}
 
			ans += tmp + 1;
 
			if(tmp != 0) {
				int r_id = -1;
				int r_time = INT_MAX;
 
				for(const auto &e : desks.front()) {
					if(r_time > e.second) {
						r_id = e.first;
						r_time = e.second;
					}
				}
 
				ans += 1;
				desks.front().erase(r_id);
 
				int to = m;
				for(int i = 1; i < m; ++i) {
					if(desks[i].size() < c) {
						desks[i].insert({r_id, r_time});
						to = i;
						break;
					}
				}
 
				ans += to + 1;
 
				if(tmp < m) desks[tmp].erase(id);
				ans += tmp + 1;
 
				desks.front().insert({id, t});
				ans += 1;
			}
		}
 
 
		cout << ans << endl;
	}
 
	return EXIT_SUCCESS;
}
accuracy: 1
time_ms: 20
memory_kb: 1256
final_rank: 9

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

#define dump(a) (cerr << #a << " = " << (a) << endl)

#define REP(i,a,b) for(int i=(a);i < (int)(b); i++)
#define rep(i,n) REP(i,0,n)
#define ALL(v) begin(v), end(v)

int main(){
  for(int m, c, n; cin >> m >> c >> n && m;) {
    vector<unordered_map<int, int>> desks(m);

    queue<int> que;
    vector<int> index(n, 0);
    vector<vector<int>> books(n);

    for(int i = 0; i < n; ++i) {
      que.push(i);

      int k;
      cin >> k;

      for(int j = 0; j < k; ++j) {
	int b;
	cin >> b;
	books[i].emplace_back(b);
      }
    }

    int ans = 0;
    for(int t = 0; !que.empty(); ++t) {
      const int student = que.front();
      que.pop();

      const int id = books[student][index[student]];
      if(++index[student] < books[student].size()) {
	que.push(student);
      }

      int pos = m;
      for(int i = 0; i < m; ++i) {
	if(desks[i].count(id)) {
	  desks[i].erase(id);
	  pos = i;
	  break;
	}
      }

      ans += pos + 1;

      int tmp = m;
      for(int i = 0; i < m; ++i) {
	if(desks[i].size() < c) {
	  desks[i].insert({id, t});
	  tmp = i;
	  break;
	}
      }

      ans += tmp + 1;

      if(tmp != 0) {
	int r_id = -1;
	int r_time = INT_MAX;

	for(const auto &e : desks[0]) {
	  if(r_time > e.second) {
	    r_id = e.first;
	    r_time = e.second;
	  }
	}

	ans += 1;
	desks[0].erase(r_id);

	int to = m;
	for(int i = 1; i < m; ++i) {
	  if(desks[i].size() < c) {
	    desks[i].insert({r_id, r_time});
	    to = i;
	    break;
	  }
	}

	ans += to + 1;

	if(tmp < m) desks[tmp].erase(id);
	ans += tmp + 1;

	desks[0].insert({id, t});
	ans += 1;
      }
    }


    cout << ans << endl;
  }

  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 1264
final_rank: 10

code_snippet: #include<algorithm>
#include<bitset>
#include<cctype>
#include<cmath>
#include<complex>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<numeric>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#include<vector>

#define repi(i,a,b) for(int i = int(a); i < int(b); i++)
#define rep(i,a) repi(i,0,a)
#define repd(i,a,b) for(int i = int(a); i >= int(b); i--)
#define repit(i,a) for(__typeof((a).begin()) i = (a).begin(); i != (a).end(); i++)
#define all(u) (u).begin(),(u).end()
#define rall(u) (u).rbegin(),(u).rend()
#define UNIQUE(u) (u).erase(unique(all(u)),(u).end())
#define pb push_back
#define mp make_pair
const double pi = acos(-1.0);

using namespace std;

typedef long long ll;

int m, c, n;
signed main(){
    while(cin >> m >> c >> n, m||c||n) {
        vector<vector<int> > b(n);
        rep(i, n) {
            int k;
            cin >> k;
            b[i].resize(k);
            rep(j, k) cin >> b[i][j];
        }

        vector<int> book;
        queue<pair<int, int> > q;
        rep(i, n) q.push(mp(i, 0));
        while(!q.empty()) {
            int id = q.front().first;
            int index = q.front().second;
            q.pop();
            if(index == b[id].size()) continue;
            book.pb(b[id][index]);
            q.push(mp(id, index+1));
        }
        
        int ans = 0;
        vector<vector<int> > D(m);
        vector<int> place(101);
        rep(i, 101) place[i] = m;

        rep(i, book.size()) {
            int nbook = book[i];
            // take book
            ans += place[nbook] + 1;
            if(place[nbook] != m) {
                vector<int>::iterator itr = find(all(D[place[nbook]]), nbook);
                D[place[nbook]].erase(itr, itr+1);
            }
//            cout << "place of " << i << "th book : " << place[nbook] << endl;
            if(D[0].size() == c) {
                // 1
                int closest = -1;
                rep(j, m) if(D[j].size() < c) {
                    closest = j;
                    break;
                }
                if(closest >= 0) {
                    place[nbook] = closest;
                    ans += closest + 1;
                    D[closest].pb(nbook);
                } else {
                    place[nbook] = m;
                    ans += m+1;
                }
//                cout << i << ", 1 : " << ans << endl;
                
                // 2
                int oldest = D[0][0];
                D[0].erase(D[0].begin(), D[0].begin() + 1);
                ans++;
//                cout << i << ", 2 : " << ans << endl;

                // 3
                closest = -1;
                repi(j, 1, m) if(D[j].size() < c) {
                    closest = j;
                    break;
                }
                if(closest >= 0) {
                    place[oldest] = closest;
                    ans += closest + 1;
                    D[closest].pb(oldest);
                } else {
                    place[oldest] = m;
                    ans += m+1;
                }
//                cout << i << ", 3 : " << ans << endl;

                // 4
                ans += place[nbook] + 1;
                if(place[nbook] != m) {
                    vector<int>::iterator itr = find(all(D[place[nbook]]), nbook);
                    D[place[nbook]].erase(itr, itr+1);
                }
//                cout << i << ", 4 : " << ans << endl;

                // 5
                D[0].pb(nbook);
                place[nbook] = 0;
                ans++;
//                cout << i << ", 5 : " << ans << endl;
                
            } else {
                D[0].pb(nbook);
                place[nbook] = 0;
                ans++;
            }
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1300
final_rank: 6

code_snippet: #include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<cstdlib>
#include<cctype>
using namespace std;
#define P pair<int, const char*>
#define REP(i, j) for(int i = 0; i < j; i++)
#define FOR(i, j, k) for(int i = j; i < k; i++)

vector<int> books;
vector< vector<int> > desks;
int ans = 0;

void replace_desks(int did){
  REP(i, desks[did].size()){
    if(desks[did][i] != -1) continue;
    FOR(j, i, desks[did].size()){
      if(desks[did][j] != -1){
        swap(desks[did][i], desks[did][j]);
        break;
      }
    }
  }
}

bool is_full(int did){
  REP(i, desks[did].size()) if(desks[did][i] == -1) return false;
  return true;
}

int take_oldbook(){
  int tmp = desks[0][0];
  desks[0][0] = -1;
  replace_desks(0);
  ans += 1;
  return tmp;
}

void put_oldbook(int book){
  FOR(i, 1, desks.size()){
    REP(j, desks[i].size()){
      if(desks[i][j] == -1){
        desks[i][j] = book;
        ans += (i + 1);
        return ;
      }
    }
  }
  ans += (desks.size() + 1);
  return ;
}

void take_book(int book){
  REP(i, desks.size()){
    REP(j, desks[i].size()){
      if(desks[i][j] == book){
        desks[i][j] = -1;
        replace_desks(i);
        ans += (i + 1);
        return ;
      }
    }
  }
  ans += (desks.size() + 1);
  return ;
}

void put_book(int book){
  REP(i, desks.size()){
    REP(j, desks[i].size()){
      if(desks[i][j] == -1){
        desks[i][j] = book;
        ans += (i + 1);
        return ;
      }
    }
  }
  ans += (desks.size() + 1);
  return ;
}

int main(){
  int m, c, n;
  while(cin >>m >>c >>n && m){
    ans = 0;
    books = vector<int>();
    desks = vector< vector<int> >(m, vector<int>(c, -1));
    vector< vector<int> > tmp(n);
    int tmp_int = 0;
    REP(i, n){
      int k; cin >>k;
      vector<int> tmp2(k);
      REP(j, k) cin >>tmp2[j];
      tmp[i] = tmp2;
      tmp_int = max(tmp_int, (int)(tmp2.size()));
    }
    REP(i, tmp_int){
      REP(j, n){
        if(i >= tmp[j].size()) continue;
        books.push_back(tmp[j][i]);
      }
    }

    REP(i, books.size()){
      take_book(books[i]);
      if(is_full(0)){
        put_book(books[i]);
        int tmp_book = take_oldbook();
        put_oldbook(tmp_book);
        take_book(books[i]);
        put_book(books[i]);
      } else{
        put_book(books[i]);
      }
    }
    cout <<ans <<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 1288
final_rank: 11

code_snippet: #include<iostream>
#include<cstdio>
#include<deque>
#include<vector>
#include<algorithm>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define inf (1<<29)
#define MAX 110
using namespace std;

struct P
{
  int id; 
  bool ex;
  P(int id=-inf,bool ex=true):id(id),ex(ex){}
};

int CNT[MAX];
deque<P> desk[MAX];
deque<int> Person[MAX];
int m,c,n,ans,rem;

int getNext(int index)
{
  while(Person[index].empty())index = (index+1)%n;
  return index;
}

void take(int index)
{
  bool ok = false;
  rep(i,m)
    {
      rep(j,desk[i].size())
	{
	  //cout << "desk[" << i << "][" << j << "] = " << desk[i][j].id << " : " << desk[i][j].ex << endl;
	  if(!desk[i][j].ex)continue;
	  if(desk[i][j].id == index)
	    {
	      desk[i][j].ex = false,ans += (i+1);
	      CNT[i]--;
	      ok = true;
	      //cout << "take from desk:" << i << " +" << (i+1) << endl;
	      return;
	    }
	}
      while(!desk[i].empty() && !desk[i].front().ex)desk[i].pop_front();
    }
  //cout << "take from shelf +" << m+1 << endl;
  ans += (m+1);
}

bool check(int index)
{
  //cout << "CNT[0]+1 = " << CNT[0]+1 << " <= " << c << endl;
  if(CNT[0]+1 <= c)
    {
      //cout << "book : " << index << " is able to put desk : " << 0 << endl;
      ans++;
      CNT[0]++;
      desk[0].push_back(P(index,true));
      return true;
    }
  return false;
}

void put(int index)
{

  if(check(index))return;
  
  //put 
  int pre=-inf;
  bool ok = false;
  rep(i,m)
    if(CNT[i]+1 <= c)
      {
	//cout << "一時的にdesk" << i << "におく　＆　そこから再度取り出す" << endl;
	CNT[i]++;
	pre = i;
	ans += (i+1)*2;
	ok = true;
	break;
      }
  if(!ok)ans += (m+1)*2;

  //take from desk 1
  ans++;
  while(!desk[0].empty() && !desk[0].front().ex)desk[0].pop_front();
  P p = desk[0].front(); desk[0].pop_front();
  CNT[0]--;
  assert(CNT[0] >= 0);
  //cout << "0番の本 " << p.id << " をとる" << endl;

  //put
  ok = false;
  REP(i,1,m)
    if(CNT[i]+1 <= c)
      {
	//cout <<"0番からの本 " << p.id << "を机" << i << "におく" << endl;  
	CNT[i]++;
	ans += (i+1);
	p.ex = true;
	desk[i].push_back(p);
	ok = true;
	break;
      }
  if(!ok)ans += (m+1);
  if(pre != -inf)CNT[pre]--;
  
  ans++;
  CNT[0]++;
  desk[0].push_back(P(index,true));
  
}

int main()
{

  while(cin >> m >> c >> n,m|n|c)
    {
      rem = n;
      ans = 0;
      rep(i,m+1)desk[i].clear(),CNT[i] = 0;
      rep(i,n)Person[i].clear();
      rep(i,n)
	{
	  int k,b;
	  cin >> k;
	  rep(j,k)
	    {
	      cin >> b;
	      Person[i].push_back(b);
	    }
	}

      int index = 0;
      while(rem)
	{
	  //cout << endl;
	  //rep(i,m)cout << "desk[" << i << "] = "<< CNT[i] << " ";
	  //cout << endl;

	  index = getNext(index);
	  //cout << "index = " << index << endl;
	  int target = Person[index].front(); Person[index].pop_front();
	  //cout << "target = " << target << endl; 
	  if(Person[index].empty())rem--;

	  take(target);
	  //cout << "after take, ans = " << ans << endl;
	  put(target);
	  //cout << "after put, ans = "<< ans << endl;
	  index = (index+1)%n;
	}
      cout << ans << endl;
    }
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 1380
final_rank: 13

code_snippet: #include<iostream>
#include<vector>

using namespace std;

const int MAX_D = 11;
int m,c,n,ans;
vector<int> req;
vector<int> D[MAX_D];

void input(){
  vector<int> tmp[n];
  int sum = 0;
  
  for(int i = 0; i < n; i++){
    int num;
    cin >> num;
    sum += num;
    for(int j = 0; j < num; j++){
      int in;
      cin >> in;
      tmp[i].push_back(in);
    }
  }
  
  int pos = 0;
  while(sum){
    for(int i = 0; i < n; i++)
      if(tmp[i].size() > pos){
	req.push_back(tmp[i][pos]);
	sum--;
      }
    pos++;
  }
  
  D[m] = req;
}

void init(){
  req.clear();
  for(int i = 0; i < MAX_D; i++)
    D[i].clear();
  ans = 0;
}

int find(int num){
  
  vector<int>::iterator ite;
  
  for(int i = 0; i <= m; i++)
    for(ite = D[i].begin(); ite < D[i].end(); ite++)
      if(*ite == num){
	D[i].erase(ite);
	return i+1;
      }
}

int ret(int num){
  int cost = 0;
  
  if(D[0].size() < c){
    D[0].push_back(num);
    return 1;
  }else{
    int minpos = m;
    for(int i = 0; i < m; i++)
      if(D[i].size() < c){
	minpos = i;
	break;
      }
    
    //from counter to minpos+1
    cost += minpos+1;
    
    int tmppos = m;
    for(int i = 0; i < m; i++)
      if(i == minpos){
	if(D[i].size()+1 < c){
	  tmppos = i;
	  break;
	}
      }else if(D[i].size() < c){
	tmppos = i;
	break;
      }
    //from 1 to (tmppos+1)
    cost+=tmppos+2;
    
    D[tmppos].push_back(D[0][0]);
    D[0].erase(D[0].begin());
    
    
    D[0].push_back(num);
    
    //from (minpos+1) to 1
    cost += minpos+2;
  }
  return cost;
}
void solve(){
  
  for(int i = 0; i < req.size(); i++){
    int fpos = find(req[i]);
    int rcos = ret(req[i]);
    ans += fpos+rcos;
  }
  cout << ans << endl;
}

int main(){
  
  while(cin >> m >> c >> n && m+c+n){
    init();
    input();
    solve();
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1352
final_rank: 7

code_snippet: #include <iostream>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;

const int MAXN = 105;
const int MAXK = 52;
const int MAXM = 12;
const int INF = 1<<28;
int M, C, N;
int K[MAXN];
int B[MAXN][MAXK];
vector<int> D[MAXM];
int size[MAXM];
int pos[MAXN];

int tottekuru(int req) {
  int res = 0;
  for(int i = 0; i < M; ++i) {
    vector<int>::iterator it
      = find(D[i].begin(), D[i].end(), req);
    if(it != D[i].end()) {
      D[i].erase(it);
      res += i+1;
      break;
    }
  }

  if(D[0].size() < size[0]) {
    D[0].push_back(req);
    res += 1;
    return res;
  }

  int i, j;
  for(i = 1; i < M; ++i) {
    if(D[i].size() < size[i]) {
      break;
    }
  }
  for(j = i; j < M; ++j) {
    if(D[j].size() + (i == j) < size[j]) {
      break;
    }
  }
  int tmp = *D[0].begin();
  D[0].erase(D[0].begin());
  D[j].push_back(tmp);
  D[0].push_back(req);
  res += i+1 + 1 + j+1 + i+1 + 1;
  return res;
}

int main() {
  while(cin >> M >> C >> N && (M|C|N)) {
    set<int> s;
    for(int i = 0; i < N; ++i) {
      cin >> K[i];
      for(int j = 0; j < K[i]; ++j) {
        cin >> B[i][j];
        s.insert(B[i][j]);
      }
    }
    ++M;
    for(int i = 0; i < M; ++i) {
      if(i+1 == M) size[i] = INF;
      else size[i] = C;
    }
    for(int i = 0; i < MAXM; ++i) D[i].clear();
    D[M-1] = vector<int>(s.begin(), s.end());

    fill(pos, pos+MAXN, 0);
    int res = 0;
    while(1) {
      bool flag = false;
      for(int i = 0; i < N; ++i) {
        if(pos[i] == K[i]) continue;
        flag = true;
        int req = B[i][pos[i]++];
        res += tottekuru(req);
      }
      if(!flag) break;
    }
    cout << res << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1252
final_rank: 4

code_snippet: #include<iostream>
#include<vector>

using namespace std;

const int MAX_D = 11;
int m,c,n,ans;
vector<int> req;
vector<int> D[MAX_D];

void input(){
  vector<int> tmp[n];
  int sum = 0;

  for(int i = 0; i < n; i++){
    int num;
    cin >> num;
    sum += num;
    for(int j = 0; j < num; j++){
      int in;
      cin >> in;
      tmp[i].push_back(in);
    }
  }
  
  int pos = 0;
  while(sum){
    for(int i = 0; i < n; i++)
      if(tmp[i].size() > pos){
	req.push_back(tmp[i][pos]);
	sum--;
      }
    pos++;
  }

  D[m] = req;
}

void init(){
  req.clear();
  for(int i = 0; i < MAX_D; i++)
    D[i].clear();
  ans = 0;
}

int find(int num){

  vector<int>::iterator ite;

  for(int i = 0; i <= m; i++)
    for(ite = D[i].begin(); ite < D[i].end(); ite++)
      if(*ite == num){
	D[i].erase(ite);
	return i+1;
      }
}

int ret(int num){
  int cost = 0;

  if(D[0].size() < c){
    D[0].push_back(num);
    return 1;
  }else{
    int minpos = m;
    for(int i = 0; i < m; i++)
      if(D[i].size() < c){
	minpos = i;
	break;
      }

    //from counter to minpos+1
    cost += minpos+1;

    int tmppos = m;
    for(int i = 0; i < m; i++)
      if(i == minpos){
	if(D[i].size()+1 < c){
	  tmppos = i;
	  break;
	}
      }else if(D[i].size() < c){
	tmppos = i;
	break;
      }
    //from 1 to (tmppos+1)
    cost+=tmppos+2;

    D[tmppos].push_back(D[0][0]);
    D[0].erase(D[0].begin());


    D[0].push_back(num);

    //from (minpos+1) to 1
    cost += minpos+2;
  }
  return cost;
}
void solve(){

  for(int i = 0; i < req.size(); i++){
    int fpos = find(req[i]);
    int rcos = ret(req[i]);
    ans += fpos+rcos;
  }
  cout << ans << endl;
}

int main(){

  while(cin >> m >> c >> n && m+c+n){
    init();
    input();
    solve();
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1352
final_rank: 7