题目原意:一个长度为N的数组中,包含正数,负数,零,请实现一个函数找出第一个最长和为零的连续子数组。
样例输入:
1 2 3 4 -1 -2 -4 -3 1 2
样例输出:
1 2 3 4 -1 -2 -4 -3
分析:此题采用递归方式求解。求第n个到最后一个的最长连续子串,可递归为解中一定包含第n个数的和解中没有第n个数(即第n+1到最后的解)。一定包含n的解应该是首先求得,第n个数到最后一个数的和,和从最后一个数开始往前减,减到和为0,就是包含第n个数的解。
代码如下:
#include<vector>
#include<iostream>
#include<utility>
using namespace std;
typedef pair<int, int> answerType;
vector<int> line;
answerType getMaxZero(int index,int sum)
{
int indexplus = line.size()-1;
if (index == line.size() - 1)
{
if (line[index] == 0)
return answerType(index, 1);
else
return answerType(index, 0);
}
answerType buf = getMaxZero(index + 1, sum - line[index]);
if (sum != 0)
{
while (indexplus > index)
{
if (sum == 0)
break;
else
sum -= line[indexplus--];
}
}
if (sum == 0)
if (buf.second <= indexplus - index)
return answerType(index, indexplus - index+1);
return buf;
}
int main()
{
while (1)
{
char s;
int i;
s=getchar();
if (s != 10)
cin.putback(s);
else
break;
cin >> i;
line.push_back(i);
}
answerType s = getMaxZero(0,accumulate(line.begin(),line.end(),0));
for (int i = 0; i <s.second; i++)
cout << line[s.first + i]<<' ';
}