PAT | T1004 To Buy or Not to Buy - Hard Version(待优化)

28分,有3个测试点超时,暂时还没想出怎么优化。

#include <iostream>
#include <string>
#include <unordered_map>
#include <climits>

using namespace std;

struct Beads{
	unordered_map<char,int> colors;
};

Beads shop[110];
int best = INT_MAX; // 最好情况下需要多买多少珠子
int stillneed = INT_MAX;
bool hasSolu = true;


void DFS(int i,int n,Beads need){
	if(hasSolu == false)
		return;
	unordered_map<char,int>::iterator it = shop[i].colors.begin();
	while(it != shop[i].colors.end()){ // 假设要这串珠子
		need.colors[it->first] -= it->second;
		it++;
	}
	// 看是否已经够了
	it = need.colors.begin();
	bool enough = true;
	int plus = 0; // 需要多买多少珠子
	int lack = 0; // 还差多少珠子没买
	while(it != need.colors.end()){
		if(it->second > 0){
			enough = false;
			lack += it->second;
		}else{
			plus -= it->second;
		}
		it++;
	}
	if(enough == true){ // 如果已经够了
		if(plus < best) // 找到一个更好的解
			best = plus;
	}else{ // 不够则继续递归向下
		if(i < n - 1 && plus <= best)
			DFS(i + 1,n,need);
		else if(i == n - 1 && best == INT_MAX && stillneed > lack){
			stillneed = lack;
			hasSolu = false;
		}
	}
	it = shop[i].colors.begin();
	while(it != shop[i].colors.end()){
		need.colors[it->first] += it->second;
		it++;
	} // 假设不要当前这串珠子
	if(i < n - 1)
		DFS(i + 1,n,need);
	return;
}

int main(){
	string buy;
	int n;
	cin>>buy>>n;
	Beads want;
	for(int i = 0;i < buy.length();i++){
		want.colors[buy[i]]++;
	}
	for(int i = 0;i < n;i++){
		string temp;
		cin>>temp;
		for(int j = 0;j < temp.length();j++){
			shop[i].colors[temp[j]]++;
		}
	}
	DFS(0,n,want);
	if(best < INT_MAX){
		printf("Yes %d",best);
	}
	else{
		printf("No %d",stillneed);
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值