1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 int n, C; 5 int nc, nw; 6 int ans; 7 int cost[60][3], weight[60][3]; 8 void dfs(int i) { 9 if (i == n) ans= min(ans, nw); 10 for (int j = 0; j < 3; j++) { 11 nc += cost[i][j]; 12 nw += weight[i][j]; 13 if (nc < C&&nw<ans) 14 dfs(i + 1); 15 nc -= cost[i][j]; 16 nw -= weight[i][j]; 17 } 18 } 19 int main() { 20 while (cin >> n >> C) { 21 for (int i = 0; i < n; i++) { 22 for (int j = 0; j < 3; j++) { 23 cin >> weight[i][j] >> cost[i][j]; 24 } 25 } 26 ans = 0x3f3f3f3f; 27 dfs(0); 28 cout << ans<<endl; 29 } 30 return 0; 31 }
题意:输入两个数n,C表示以下n行,之后每行6个数,两个数一组,第一个数表示该部件质量,第二个数表示该部件的花费。要求在总cost<C的条件下,从每行选一个部件,使得总质量最小。
思路:
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 int n, C; 5 int nc, nw; 6 int ans; 7 int cost[60][3], weight[60][3]; 8 void dfs(int i) { 9 if (i == n) ans= min(ans, nw); 10 for (int j = 0; j < 3; j++) { 11 nc += cost[i][j]; 12 nw += weight[i][j]; 13 if (nc < C&&nw<ans) 14 dfs(i + 1); 15 nc -= cost[i][j]; 16 nw -= weight[i][j]; 17 } 18 } 19 int main() { 20 while (cin >> n >> C) { 21 for (int i = 0; i < n; i++) { 22 for (int j = 0; j < 3; j++) { 23 cin >> weight[i][j] >> cost[i][j]; 24 } 25 } 26 ans = 0x3f3f3f3f; 27 dfs(0); 28 cout << ans<<endl; 29 } 30 return 0; 31 }