Solution -「CF 802C」Heidi and Library (hard)
阿新 • • 發佈:2020-08-01
\(\mathcal{Descriptoin}\)
Link.
你有一個容量為 \(k\) 的空書架,現在共有 \(n\) 個請求,每個請求給定一本書 \(a_i\)。如果你的書架裡沒有這本書,你就必須以 \(c_{a_i}\) 的價格購買這本書放入書架。當然,你可以在任何時候丟掉書架裡的某本書。請求出完成這 \(n\) 個請求所需要的最少價錢。
\(n,k\le80\)。
\(\mathcal{Solution}\)
網路瘤嘛……
費用流,考慮先全部買入,再抵消花費。具體地,假設 \(i<j\),第 \(i\) 天的書和第 \(j\) 天的書相同,就可以一直保留第 \(i\)
- \(S\) 向 \(v_i~(i=1,2,\dots n)\) 連邊,容量為 \(1\),費用為 \(c_{a_i}\),表示買入。
- \(v_i\) 向 \(v_{i+1}~(i=1,2,\cdots,n-1)\) 連邊,容量為 \(k-1\),費用為 \(0\),表示保留至多 \(k-1\) 本,剩下一本給 \(a_{i+1}\) 留位置。
- \(v_i\) 向 \(v_i'~(i=1,2,\cdots,n)\) 連邊,容量為 \(1\),費用為 \(0\),表示將這本書出手(丟掉或賣掉)。
- \(v_{i-1}\) 向上一次 \(a_i\)
- \(v_i'\) 向 \(T\) 連邊,容量為 \(1\),費用為 \(0\)。
費用流求出的最小費用就是答案。
\(\mathcal{Code}\)
#include <queue> #include <cstdio> typedef std::pair<int, int> pii; const int MAXN = 80, MAXND = MAXN * 2 + 2, MAXED = 5 * MAXN, INF = 0x3f3f3f3f; int n, K, S, T, ecnt = 1, a[MAXN + 5], c[MAXN + 5], las[MAXN + 5]; int head[MAXND + 5], curh[MAXND + 5], d[MAXND + 5]; bool vis[MAXND + 5]; struct Edge { int to, flow, cost, nxt; } graph[MAXED * 2 + 5]; inline void link ( const int s, const int t, const int f, const int c ) { graph[++ ecnt] = { t, f, c, head[s] }; head[s] = ecnt; } inline void addEdge ( const int s, const int t, const int f, const int c ) { link ( s, t, f, c ), link ( t, s, 0, -c ); } inline pii DFS ( const int u, int iflow ) { vis[u] = true; if ( u == T ) return { iflow, 0 }; int oflow = 0, ocost = 0; for ( int& i = curh[u], v; i; i = graph[i].nxt ) { if ( ! vis[v = graph[i].to] && d[v] == d[u] + graph[i].cost && graph[i].flow ) { pii of ( DFS ( v, std::min ( iflow, graph[i].flow ) ) ); oflow += of.first, ocost += of.first * graph[i].cost + of.second; graph[i].flow -= of.first, graph[i ^ 1].flow += of.first; if ( ! ( iflow -= of.first ) ) break; } } if ( ! oflow ) d[u] = INF; return { oflow, ocost }; } inline bool SPFA () { static std::queue<int> que; static bool inq[MAXND + 5]; for ( int i = 0; i <= T; ++ i ) d[i] = INF, inq[i] = false; que.push ( S ), d[S] = 0, inq[S] = true; for ( int u; ! que.empty (); ) { inq[u = que.front ()] = false, que.pop (); for ( int i = head[u], v; i; i = graph[i].nxt ) { if ( d[v = graph[i].to] > d[u] + graph[i].cost && graph[i].flow ) { d[v] = d[u] + graph[i].cost; if ( ! inq[v] ) que.push ( v ), inq[v] = true; } } } return d[T] ^ INF; } inline int Dinic () { int ret = 0; for ( ; SPFA (); ret += DFS ( S, INF ).second ) { for ( int i = 0; i <= T; ++ i ) { vis[i] = false; curh[i] = head[i]; } } return ret; } int main () { scanf ( "%d %d", &n, &K ); for ( int i = 1; i <= n; ++ i ) scanf ( "%d", &a[i] ); for ( int i = 1; i <= n; ++ i ) scanf ( "%d", &c[i] ); S = 0, T = n << 1 | 1; for ( int i = 1; i <= n; ++ i ) { addEdge ( S, i, 1, c[a[i]] ), addEdge ( i, i + n, 1, 0 ); if ( las[a[i]] ) addEdge ( i - 1, las[a[i]] + n, 1, -c[a[i]] ); if ( i < n ) addEdge ( i, i + 1, K - 1, 0 ); addEdge ( i + n, T, 1, 0 ), las[a[i]] = i; } printf ( "%d\n", Dinic () ); return 0; }