#include #include #include #include #include #include #include #include #include #include using namespace std; template class Min_Cost_Flow{ public: struct edge{ int to; int cap; T cost; int rev; bool reverse; }; const T INF; vector> G; Min_Cost_Flow(int n, T inf) : G(n), INF(inf){ } void add_edge(int from, int to, int cap, T cost){ G[from].push_back((edge){to, cap, cost, (int)G[to].size(), false}); G[to].push_back((edge){from, 0, -cost, (int)G[from].size()-1, true}); } //min cost : s->t (flow:f) T min_cost_flow(int s, int t, int f){ T cost = 0; vector prev_v(G.size(),-1); vector prev_e(G.size(),-1); vector potantial(G.size(), 0); vector dist(G.size(), INF); dist[s] = 0; /*bellman_ford*/{ bool update = true; for(int cnt = 0; update; cnt++){ update = false; for(int i=0; i= INF) continue; for(int j=0; j 0 && dist[G[i][j].to] > dist[i] + G[i][j].cost){ dist[G[i][j].to] = dist[i] + G[i][j].cost; update = true; } } } if(update && cnt >= G.size()){ cerr << " there is a negative cycle " << endl; return -1; } cnt++; } for(int i=0; i0){ fill(dist.begin(), dist.end(), INF); dist[s] = 0; prev_v[s] = s; /*dijkstra*/{ priority_queue, vector>, greater>> pq; pq.push({0, s}); while(pq.size()){ pair p = pq.top(); pq.pop(); if(dist[p.second] < p.first) continue; dist[p.second] = p.first; for(int i=0; i 0 && dist[e.to] > new_dist){ dist[e.to] = new_dist; prev_v[e.to] = p.second; prev_e[e.to] = i; pq.push({dist[e.to], e.to}); } } } } if(potantial[t] + dist[t] == INF){ cerr << "couldn't insert flow f : " << f << endl; return -1; } for(int i=0; i> get_edge_info(){ vector> E(G.size()); for(int i=0; i> n; int x; cin >> x; vector a(x); for(int i=0; i>a[i];} random_shuffle(a.begin(), a.end()); int y; cin >> y; vector b(y); for(int i=0; i>b[i];} random_shuffle(b.begin(), b.end()); int sz_x = (n/x + (n%x==0?0:1)) * x; int sz_y = (n/y + (n%y==0?0:1)) * y; int sz = sz_x + sz_y + 2; int s = sz_x + sz_y + 0; int t = sz_x + sz_y + 1; Min_Cost_Flow flow(sz, 1e8); vector offset_x; for(int k=0; k offset_y; for(int k=0; kb[(j-sz_x)%y]?0:1) ); } } long long ans = 0; for(int i=0; i> v; for(int i=0; i= sz_x) continue; for(int j=0; j " << e[i][j]-sz_x << " : "; cerr << a[i%x] << " -> " << b[(e[i][j]-sz_x)%y] << endl; v[a[i%x]].push_back(b[(e[i][j]-sz_x)%y]); } } for(int i=0; i