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