以此题开始进入学习状压dp~
题目大意
输入每瓶维生素的价格以及所含维生素元素,若能买到包含abc三种维生素,输出所需最小价钱,否则输出-1.
题解
状压dp,每种维生素对应一位,求出数值7(即二进制111)所对应的价格
代码
1 #include <iostream> 2 #include <string> 3 #include <algorithm> 4 using namespace std; 5 6 int main() 7 { 8 int dp[8], tmp[8], n, c; 9 string s; 10 cin >> n; 11 for (int i = 0; i <= 7; i++) dp[i] = 0x3f3f3f3f, tmp[i] = 0; 12 for (int i = 0; i < n; i++) { 13 cin >> c >> s; 14 for (int j = 0; j < s.size(); j++) { 15 if (s[j] == ‘A‘) tmp[i] |= 1; 16 if (s[j] == ‘B‘) tmp[i] |= 2; 17 if (s[j] == ‘C‘) tmp[i] |= 4; 18 } 19 dp[tmp[i]] = min(dp[tmp[i]], c); 20 } 21 for (int i = 0; i <= 7; i++) 22 for (int j = 0; j <= 7; j++) 23 dp[i | j] = min(dp[i | j], dp[i] + dp[j]); 24 if (dp[7] < 0x3f3f3f3f) cout << dp[7] << endl; 25 else cout << -1 << endl; 26 27 }
原文地址:https://www.cnblogs.com/komorabi/p/10671804.html
时间: 2024-11-14 12:28:21