Problem Description
传送门
Master QWsin is dating with Sindar. And now they are in a restaurant, the restaurant has n dishes in order. For each dish, it has a delicious value ai. However, they can only order k times. QWsin and Sindar have a special ordering method, because they believe that by this way they can get maximum happiness value.
Specifically, for each order, they will choose a subsequence of dishes and in this subsequence, when i<j, the subsequence must satisfies ai≤aj. After a round, they will get the sum of the subsequence and they can’t choose these dishes again.
Now, master QWsin wants to know the maximum happiness value they can get but he thinks it’s too easy, so he gives the problem to you. Can you answer his question?
Input
There are multiple test cases. The first line of the input contains an integer T, indicating the number of test cases. For each test case:
First line contains two positive integers n and k which are separated by spaces.
Second line contains n positive integer a1,a2,a3…an represent the delicious value of each dish.
1≤T≤5
1≤n≤2000
1≤k≤10
1≤ai≤1e5
Output
Only an integer represent the maximum happiness value they can get.
Sample Input
1
9 2
5 3 2 1 4 2 1 4 6
Sample Output
22
#include <iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<map>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int INF=0x3f3f3f3f;
const int NINF=0xc0c0c0c0;
const int MAX_N=2000+5;
struct edge{
int to,cap,cost,rev;
};
int n,V,k;
int a[MAX_N];
vector<edge> G[2*MAX_N+2];
int h[2*MAX_N+2];
int dist[2*MAX_N+2];
int prevv[2*MAX_N+2],preve[2*MAX_N+2];
void add_edge(int from,int to,int cap,int cost){
G[from].push_back((edge){to,cap,cost,G[to].size()});
G[to].push_back((edge){from,0,-cost,G[from].size()-1});
}
int min_cost_flow(int s,int t,int f){
int res=0;
fill(h,h+V,0);
while(f>0){
priority_queue<P,vector<P>,greater<P> >que;
fill(dist,dist+V,INF);
dist[s]=0;
que.push(P(0,s));
while(!que.empty()){
P p=que.top();que.pop();
int v=p.second;
if(dist[v]<p.first)continue;
for(int i=0;i<G[v].size();i++){
edge &e=G[v][i];
if(e.cap>0&&dist[e.to]>dist[v]+e.cost+h[v]-h[e.to]){
dist[e.to]=dist[v]+e.cost+h[v]-h[e.to];
prevv[e.to]=v;
preve[e.to]=i;
que.push(P(dist[e.to],e.to));
}
}
}
if(dist[t]==INF)return -1;
for(int v=0;v<V;v++)h[v]+=dist[v];
int d=f;
for(int v=t;v!=s;v=prevv[v]){
d=min(d,G[prevv[v]][preve[v]].cap);
}
f-=d;
res+=d*h[t];
for(int v=t;v!=s;v=prevv[v]){
edge &e=G[prevv[v]][preve[v]];
e.cap-=d;
G[v][e.rev].cap+=d;
}
}
return res;
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
scanf("%d",a+i);
}
V=n*2+2;
int s=0,t=V-1;
for(int i=1;i<=n;i++){
add_edge(s,i,1,0);
add_edge(i,i+n,1,-a[i]);
add_edge(i+n,t,1,0);
}
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(a[i]<=a[j])add_edge(i+n,j,1,0);
}
}
printf("%d\n",-min_cost_flow(s,t,min(k,n)));
for(int i=0;i<V;i++)G[i].clear();
}
return 0;
}