gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
fi=open('VANCHUYEN.INP','r') fo=open('VANCHUYEN.OUT','w')…
- User
fi=open('VANCHUYEN.INP','r') fo=open('VANCHUYEN.OUT','w') line=fi.readline().strip().split() t,n=int(line[0]),int(line[1]) a=[] for i in range(n): x=int(fi.readline().strip()) a.append(x) d=[] for i in range(t+1): d.append(0) d[0]=1 for i in range(n): for j in range(t,a[i]-1,-1): if d[j-a[i]]==1: d[j]=1 i=t while i>=0 and d[i]==0: i-=1 if i>0: fo.write(str(i)) else: fo.write('0') fo.close() Chuyển sang viết theo C++
- Assistant
Certainly! Below is the equivalent C++ code for the given Python code.
#include <iostream> #include <fstream> #include <vector> int main() { std::ifstream fi("VANCHUYEN.INP"); std::ofstream fo("VANCHUYEN.OUT"); int t, n; fi >> t >> n; std::vector<int> a(n); for (int i = 0; i < n; ++i) { fi >> a[i]; } std::vector<int> d(t+1, 0); d[0] = 1; for (int i = 0; i < n; ++i) { for (int j = t; j >= a[i]; --j) { if (d[j - a[i]] == 1) { d[j] = 1; } } } int i = t; while (i >= 0 && d[i] == 0) { --i; } if (i > 0) { fo << i; } else { fo << "0"; } fi.close(); fo.close(); return 0; }Explanation:
- This C++ program essentially follows the same logic as the Python code provided.
- It begins by reading from
VANCHUYEN.INPand writing output toVANCHUYEN.OUT.