K Subsequence
Time Limit: 2000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3577 Accepted Submission(s): 898
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
很显然的费用流。
但是非常毒瘤,卡了spfa,zkw也过不去。
必须Dijkstra势函数优化的EK才能过,而且前向星也会TLE,必须vector建图。
对每个物品拆点限流即可。
AC代码:
#pragma GCC optimize(2)
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int inf=0x3f3f3f3f;
const int N=4e3+10;
int T,n,k,s,ss,t,a[N],d[N],h[N],v[N],e[N],res;
struct node{int to,flow,w,re;};
vector<node> g[N];
inline void add(int a,int b,int c,int d){
g[a].push_back({b,c,d,g[b].size()}); g[b].push_back({a,0,-d,g[a].size()-1});
}
priority_queue<pair<int,int> > q;
inline int dijkstra(){
memset(d,0x3f,sizeof d); d[s]=0; q.push({0,s});
while(!q.empty()){
int u=q.top().second,val=q.top().first; q.pop();
if(d[u]<-val) continue;
for(int i=0,m=g[u].size();i<m;i++){
int to=g[u][i].to,w=g[u][i].w,flow=g[u][i].flow;
if(flow&&d[to]>d[u]+w+h[u]-h[to]){
d[to]=d[u]+w+h[u]-h[to];
v[to]=u; e[to]=i; q.push({-d[to],to});
}
}
}
for(int i=s;i<=t;i++) h[i]+=d[i];
return d[t]!=inf;
}
int EK(){
while(dijkstra()){
int mi=inf;
for(int i=t;i!=s;i=v[i]) mi=min(mi,g[v[i]][e[i]].flow);
for(int i=t;i!=s;i=v[i]){
node &p=g[v[i]][e[i]]; p.flow-=mi; g[i][p.re].flow+=mi;
}
res+=h[t]*mi;
}
return -res;
}
signed main(){
cin>>T;
while(T--){
scanf("%d %d",&n,&k); ss=n*2+1; t=ss+1;
for(int i=0;i<=t;i++) g[i].clear(); res=0;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]),add(i,i+n,1,-a[i]),add(ss,i,1,0),add(i+n,t,1,0);
add(s,ss,k,0);
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++) if(a[i]<=a[j]) add(i+n,j,1,0);
}
printf("%d\n",EK());
}
return 0;
}