#include<map> #include<iostream> #include<vector> #include<set> using namespace std; void get(vector<int> a) { vector<int> num; int i = 0; map<int, int> ma; num.push_back(0); num.push_back(a[0]); for (i = 1; i < a.size(); i++) { num.push_back(num[i] + a[i]); } for (i = 0; i < num.size(); i++) { ma[num[i]]++; } set<int> fi; map<int, int>::iterator it; for (it = ma.begin(); it != ma.end();it++) { if (it->second>1) { fi.insert(it->first); } } int j = 0, n = 0, first = 0, last = 0; for (i = 0; i < num.size(); i++) { if (fi.find(num[i]) != fi.end()) { for (j = i; j < num.size(); j++) { if (num[i] == num[j]) if (j - i>n) { n = j - i; first = i; last = j; //cout << i<<" "<<j<<num[i] << " " << num[j]<<endl; } } } } /* for (j = 0; j < num.size(); j++) { for (i = 0; i <= j; i++) { if (num[i] == num[j]) if (j - i>n) { n = j - i; first = i; last = j; //cout << i<<" "<<j<<num[i] << " " << num[j]<<endl; } } } */ for (i = first; i < last; i++) cout << a[i] << " "; } int main() { int x; vector<int> a={1,2,3,4,-4,-3,-1,-2,5,6} ; get(a); }
思想:i < j;
sum[i] = a[0] + ...+ a[i];
sum[j] = a[0] + ...+ a[j];
如果sum[i]和sum[j]相等,则a[i + 1] + ... + a[j] = 0;
时间: 2024-10-27 10:00:20