【NOIP模拟题】【DP】2016.11.10 第二题题解

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

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值