09 K Subsequence
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; ll mincost; int n, m, cnt, s, t, ts; struct node { int to, nex, val, cost; }E[4012005]; int head[4005]; int cur[4005]; void addedge(int u, int v, int va, int co) { E[++cnt].to = v; E[cnt].nex = head[u]; head[u] = cnt; E[cnt].val = va; E[cnt].cost = co; E[++cnt].to = u; E[cnt].nex = head[v]; head[v] = cnt; E[cnt].val = 0; E[cnt].cost = -co; } struct no1 { int to, edge; }pre[4005]; int dis[4005]; bool inque[4005]; int que[4000005]; bool spfa() { for(int i = 1; i <= t; i++) dis[i] = INF, inque[i] = 0, cur[i] = head[i]; dis[s] = 0; inque[s] = 1; int top = 0; que[++top] = s; while(top) { int u = que[top]; top--; inque[u] = 0; for(int i = head[u]; i; i = E[i].nex) { int v = E[i].to; if(E[i].val && dis[v] > dis[u] + 1LL * E[i].cost) { dis[v] = dis[u] + 1LL * E[i].cost; pre[v].to = u; pre[v].edge = i; if(!inque[v]) { inque[v] = 1; que[++top] = v; } } } } return dis[t] != INF; } int ans, cos1; void EK() { ans = cos1 = 0; while(spfa()) { int mi = INF; for(int i = t; i != s; i = pre[i].to) { mi = min(mi, E[pre[i].edge].val); } for(int i = t; i != s; i = pre[i].to) { E[pre[i].edge].val -= mi; E[pre[i].edge ^ 1].val += mi; } //for(int i = 1; i <= n; i++) h[i] += dis[i]; ans += mi; cos1 += mi * dis[t]; } } /* ll h[4005]; ll dis[4005]; bool vvis[4005]; bool dij() { for(int i = 1; i <= t; i++) dis[i] = INF, cur[i] = head[i], vvis[i] = 0; dis[s] = 0; priority_queue< pair<int, int> > que; que.push(make_pair(0, s)); while(!que.empty()) { int u = que.top().second; que.pop(); if(vvis[u]) continue; vvis[u] = 1; for(int i = head[u]; i; i = E[i].nex) { int v = E[i].to; if(E[i].val && dis[v] + h[v] > dis[u] + 1LL * E[i].cost + h[u]) { dis[v] = dis[u] + 1LL * E[i].cost + h[u] - h[v]; que.push(make_pair(-dis[v], v)); } } } return dis[t] != INF; }*/ int q[2005]; int main() { int T; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &m); cnt = 1; memset(head, 0, sizeof(head)); for(int i = 1; i <= n; i++) scanf("%d", &q[i]); s = n * 2 + 1; ts = s + 1; t = ts + 1; for(int i = 1; i <= n; i++) { for(int j = i + 1; j <= n; j++) { if(q[i] <= q[j]) addedge(i + n, j, 1, 0); } } for(int i = 1; i <= n; i++) addedge(s, i, 1, 0), addedge(i + n, ts, 1, 0), addedge(i, i + n, 1, -q[i]); addedge(ts, t, m, 0); EK(); printf("%d ", -cos1); } return 0; } /* 1 9 2 5 3 2 1 4 2 1 4 6 */