pat-top 1004. To Buy or Not to Buy - Hard Version (35)

7 篇文章 0 订阅

https://www.patest.cn/contests/pat-t-practise/1004


dfs+剪枝,但是依然有2个case TLE,最后像http://blog.csdn.net/jtjy568805874/article/details/50759483 使用了寻找近似解的方法。

#include <cstdio>
#include <iostream>
#include <string>
#include <climits>
#include <cstring>
#define _CRT_NONSTDC_NO_WARNINGS

using namespace std;

const int limitn = 200;
string items[102];
int colors[256];
bool EvaColors[256];
int nColors,n, need;
int minCost = INT_MAX,cnt=0;
void dfs(int l,int cost) {
	cnt++; if (cnt > limitn) return;
	if (minCost < cost) return ;
	if (l == n) return;
	int len = items[l].length();
	int currentColors[256];
	for (int i = 0; i < 256; i++)
	{
		currentColors[i] = colors[i];
	}
	int currentNeed = need;
	int currentCost = cost;
	//Buy
	for (int i = 0; i < len; i++)
	{
		if (colors[(int)items[l][i]] !=0) {
			colors[(int)items[l][i]]--;
			need--;
		}
		else {
			cost++;
		}
	}

	if (need == 0) {
		if (minCost > cost) {
			minCost = cost;
		}
	}
	dfs(l + 1, cost);

	//not Buy
	for (int i = 0; i < 256; i++)
	{
		colors[i] = currentColors[i];
	}
	need = currentNeed;
	dfs(l + 1, currentCost);
}

int main()
{
	string a,b;
	int pre_n;
	cin >> a >> pre_n;
	memset(colors, 0, sizeof(colors));
	memset(EvaColors, false, sizeof(colors));
	nColors = a.length();
	need = nColors;
	for (int i = 0; i < nColors; i++)
	{
		colors[(int)a[i]]++;
		EvaColors[(int)a[i]] = true;
	}

	for (int i = 0; i < pre_n; i++)
	{
		cin >> b;
		int len = b.length();
		bool isUseful = false;
		for (int j = 0; j < len; j++)
		{
			if (EvaColors[(int)b[j]]) isUseful = true;
			if (colors[(int)b[j]] != 0) {
				colors[(int)b[j]] --;
				need--;
			}

		}
		if (isUseful) items[n++] = b;
	}
	if (need != 0) {
		printf("No %d\n", need);
		return 0;
	}
	for (int i = 0; i < nColors; i++)
	{
		colors[(int)a[i]]++;
	}
	need = nColors;
	dfs(0,0);
	printf("Yes %d\n", minCost);
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值