tôi muốn hỏi về C++
- User
tôi muốn hỏi về C++
- Assistant
Rất vui được giúp bạn với câu hỏi về ngôn ngữ lập trình C++. Hãy đặt câu hỏi cụ thể, và tôi sẽ cố gắng trả lời một cách tốt nhất.
- User
time limit per test1 second memory limit per test64 megabytes inputstandard input outputstandard output The array a=[a1,a2,…,an] (1≤ai≤n ) is given. Its element ai is called special if there exists a pair of indices l and r (1≤l<r≤n ) such that ai=al+al+1+…+ar . In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).
Print the number of special elements of the given array a .
For example, if n=9 and a=[3,1,4,1,5,9,2,6,5] , then the answer is 5 :
a3=4 is a special element, since a3=4=a1+a2=3+1 ; a5=5 is a special element, since a5=5=a2+a3=1+4 ; a6=9 is a special element, since a6=9=a1+a2+a3+a4=3+1+4+1 ; a8=6 is a special element, since a8=6=a2+a3+a4=1+4+1 ; a9=5 is a special element, since a9=5=a2+a3=1+4 . Please note that some of the elements of the array a may be equal — if several elements are equal and special, then all of them should be counted in the answer.
- Assistant
Để giảm bộ nhớ sử dụng trong code của bạn, bạn có thể thay thế việc sử dụng mảng
precó kích thướcn+1bằng việc sử dụng một biếnsumđể tính tổng từng dãy con liên tiếp trong một vòng lặp duy nhất.Dưới đây là code sau khi chỉnh sửa:
code#include <iostream> #include <map> using namespace std; int main() { int t; cin >> t; while (t--) { int ans = 0; int n; cin >> n; map<int, int> doly; for (int i = 1; i <= n; i++) { int a; cin >> a; int sum = a; for (int j = i + 1; j <= n; j++) { sum += a[j]; doly[sum]++; } } for (int i = 1; i <= n; i++) { if (doly[a[i]] != 0) ans++; } cout << ans << endl; } return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.