[luoguP1494] 岳麓山上打水 && [luoguP2744] [USACO5.3]量取牛奶Milk Measuring

传送门

传送门

 

dfs选取集合,dp背包判断

虽然我觉的会TLE。。

但是的确是AC了

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 20001

int n, m;
int a[N];
bool vis[N], f[N];

inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
	for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
	return x * f;
}

inline void dp(int k)
{
	int i, j;
	memset(f, 0, sizeof(f));
	f[0] = 1;
	for(i = 1; i <= m; i++)
		if(vis[i])
			for(j = a[i]; j <= n; j++)
				if(f[j - a[i]])
					f[j] = 1;
	if(!f[n]) return;
	printf("%d ", k);
	for(i = 1; i <= m; i++)
		if(vis[i])
			printf("%d ", a[i]);
	exit(0);
}

inline void dfs(int cnt, int k, int last)
{
	if(cnt > k)
	{
		dp(k);
		return;
	}
	int i;
	for(i = last + 1; i <= m; i++)
		if(!vis[i])
		{
			vis[i] = 1;
			dfs(cnt + 1, k, i);
			vis[i] = 0;
		}
}

int main()
{
	int i;
	n = read();
	m = read();
	for(i = 1; i <= m; i++) a[i] = read();
	std::sort(a + 1, a + m + 1); 
	for(i = 1; i <= m; i++) dfs(1, i, 0);
	return 0;
}

  

posted @ 2017-08-08 10:23  zht467  阅读(141)  评论(0编辑  收藏  举报