题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6611
K Subsequence
Time Limit: 2000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2024 Accepted Submission(s): 471
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
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
Source
2019 Multi-University Training Contest 3
题目大意:
有一个n个数的数组,从中拿出k个不重复的不下降子序列,求这些序列的权值最大和
思路:
这道题和网络流的最长不下降子序列问题非常类似。建图的时候可以借鉴该题的思路。
1.对于每个点i,将它拆成两个点ia和ib,在这两个点之间建立一条容量为1,费用为-a[i],表示这个点只能选一次,选了之后可以得到a[i](因为求最大值,所以费用为负)
2.建立超级源点和汇点,从源点向ia建立一条容量为1,费用为0的边,再从ib向汇点建立一条容量为1,费用为0的边
3.对于i点和j点,如果有i
跑一遍最小费用最大流即可。
注意这题不能用spfa板子,会超时,从网上找了一个dijkstra版的最小费用最大流板子,仅供参考。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
ps:放一个最长不下降子序列的代码:
#include
#include
#include
#include
using namespace std;
const int Ni = 1010;
const int MAX = 1<<26;
int a[Ni],dp[Ni];
struct Edge
{
int u,v,c;
int next;
} edge[20*Ni];
int n,m;
int edn;//边数
int p[Ni];//父亲
int d[Ni];
int sp,tp;//原点,汇点
void addedge(int u,int v,int c)
{
edge[edn].u=u;
edge[edn].v=v;
edge[edn].c=c;
edge[edn].next=p[u];
p[u]=edn++;
edge[edn].u=v;
edge[edn].v=u;
edge[edn].c=0;
edge[edn].next=p[v];
p[v]=edn++;
}
int bfs()
{
queue q;
memset(d,-1,sizeof(d));
d[sp]=0;
q.push(sp);
while(!q.empty())
{
int cur=q.front();
q.pop();
for(int i=p[cur]; i!=-1; i=edge[i].next)
{
int u=edge[i].v;
if(d[u]==-1 && edge[i].c>0)
{
d[u]=d[cur]+1;
q.push(u);
}
}
}
return d[tp] != -1;
}
int dfs(int a,int b)
{
int r=0;
if(a==tp)return b;
for(int i=p[a]; i!=-1 && r0 && d[u]==d[a]+1)
{
int x=min(edge[i].c,b-r);
x=dfs(u,x);
r+=x;
edge[i].c-=x;
edge[i^1].c+=x;
}
}
if(!r)d[a]=-2;
return r;
}
int dinic(int sp,int tp)
{
int total=0,t;
while(bfs())
{
while(t=dfs(sp,MAX))
total+=t;
}
return total;
}
int main()
{
int len=1;
scanf("%d",&n);
for(int i=1; i<=n; i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
dp[i]=1;
for(int i=1; i<=n; i++)
{
for(int j=1; j