B
【题目描述】
我们要从n 种食物选m 个出来,安排一个顺序吃掉它(们),每种食物有个美味值ai,
然后我们有k 个规则,每个规则有 xi, yi 和 ci 三个数,如果吃完第xi 种食物接下来马上吃
第yi 种食物,第j 种食物的美味值会增加ci。每种食物至多吃一个,求美味值最大的和是多
少?
【输入格式】
第一行有三个数n,m,k,k 代表有k 个规则(0<=k<=n*(n-1))。
第二行有n 个数字代表每个食物的美味值。
接下去有k 行,每行三个数xi,yi,ci。保证没有任意两个规则的xi 和yi 同时相同。
【输出格式】
一行一个数代表答案
【sample input1】
2 2 1
1 1
2 1 1
【sample output1】
3
【sample input 2】
4 3 2
1 2 3 4
2 1 5
3 4 2
【sample output 2】
12
【数据范围】
30% m<=n<=5 ,0<=ci,ai<=1e5
【题目描述】
我们要从n 种食物选m 个出来,安排一个顺序吃掉它(们),每种食物有个美味值ai,
然后我们有k 个规则,每个规则有 xi, yi 和 ci 三个数,如果吃完第xi 种食物接下来马上吃
第yi 种食物,第j 种食物的美味值会增加ci。每种食物至多吃一个,求美味值最大的和是多
少?
【输入格式】
第一行有三个数n,m,k,k 代表有k 个规则(0<=k<=n*(n-1))。
第二行有n 个数字代表每个食物的美味值。
接下去有k 行,每行三个数xi,yi,ci。保证没有任意两个规则的xi 和yi 同时相同。
【输出格式】
一行一个数代表答案
【sample input1】
2 2 1
1 1
2 1 1
【sample output1】
3
【sample input 2】
4 3 2
1 2 3 4
2 1 5
3 4 2
【sample output 2】
12
【数据范围】
30% m<=n<=5 ,0<=ci,ai<=1e5
100% m<=n<=18,0<=ci,ai<=1e9
这道题我们可以用装压DP。
预处理dp[1<<i][i]=a[i]
如果已经有m个了:for(int j=0;j<n;j++)ans=max(ans,dp[i][j]);
否则:
for(int k=0;k<n;k++)//枚举哪一个没吃
if(((i>>k)&1)==0)//如果这一位为0表示没吃
for(int j=0;j<n;j++)//枚举哪一个是最后吃的
if((1<<j)&i)//如果这一位为1表示吃了
dp[i|(1<<k)][k]=max(dp[i][j]+mp[j][k]+a[k],dp[i|(1<<k)][k]);
P.S,
今天学了一个强大的函数,简直就是装压的好伙伴
__builtin_popcount(i) 它可以直接找出i中有多少个位1
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<iomanip>
#include<ctime>
#include<climits>
#include<cctype>
#include<algorithm>
#define LL long long
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
const int maxn = 18;
LL n,m,k,x,y,z,ans;
LL a[maxn+2],c[maxn+2][maxn+2];
LL dp[maxn+2][maxn+2];
template <class T> inline void read(T &xx)
{
xx = 0;
T flag = 1;
char ch = (char)getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = (char)getchar();
}
while(ch>='0' && ch<='9')
{
xx = (xx<<1) + (xx<<3) + ch - '0';
ch = (char)getchar();
}
xx *= flag;
}
void inti()
{
read(n); read(m); read(k);
for(int i = 0; i < n; i++)
read(a[i]),dp[1 << i][i] = a[i];
for(int i = 0; i < k; i++)
{
read(x), read(y), read(z);
c[x][y] = z;
}
}
void DP()
{
for(int i = 0; i < (1 << n); i++)
{
if(__builtin_popcount(i) > m) continue;
if(__builtin_popcount(i) == m)
for(int j = 0; j < n; j++)
ans = max(ans, dp[i][j]);
if(__builtin_popcount(i) < m)
for(int k = 0; k < n; k++)
if(((i>>k) & 1) == 0)
for(int j = 0; j < n; j++)
if((1<<j) & i)
dp[i|(1<<k)][k] = max(dp[i][j]+c[j][k]+a[k], dp[i|(1<<k)][k]);
}
}
int main()
{
freopen("b.in","r",stdin);
freopen("b.out","w",stdout);
inti();
DP();
printf(AUTO,ans);
return 0;
}