您的位置:首页 > 其它

和为0的最长子序列

2015-09-25 21:11 288 查看
和为0的最长子序列问题

注意:

1、输入格式 1 2 3 4 5 6

以回车结束,应该怎么读取? 考虑两点:回车结束判断 和 数组长度未定义?

while(temp = cin.get()!='\n')

{

  cin.unget();

  cin >> temp;

  vector.pushback(temp);

}

2、输入

// ConsoleApplication11.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;
vector<int> vec;

int _tmain(int argc, _TCHAR* argv[])
{

int temp = 0;
int count = 0;
vec.clear();
while ((temp = cin.get()) != '\n')
{
cin.unget();
cin >> temp;
vec.push_back(temp);
}
int thisSum = 0;
int l = 0;
int r = 0;
int i = 0, j = 0;

for (int i = 0; i < vec.size(); i++)
{

thisSum = vec[i];
for (int j = i+1; j < vec.size(); j++)
{
thisSum += vec[j];
if (thisSum == 0 && (r - l) < (j - i))
{
l = i;
r = j;
}
}

}

cout << l << " " << r << endl;

for (int k = l; k <= r; k++)
{
cout << vec[k];
}

}

// ConsoleApplication11.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;
vector<int> vec;

int column = 0;
int Char2Int(char *a, int n);
char LastChar(char *a, int n);

int _tmain(int argc, _TCHAR* argv[])
{

char temp[10];
int a;
int count = 0;
while ((a = cin.get()) != '\n')
{
cin.unget();
cin >> temp;

vec.push_back(Char2Int(temp,8));
if (LastChar(temp, 10) == ';' && count == 0)
{
count = 1;
column = vec.size();
}

}

cout << column << "\t" << vec.size() / column;
for (int i = 0; i < vec.size(); i++)
{
if (i%column == 0)
{
cout << endl;
}
cout << vec[i] << "\t";

}

}

int Char2Int(char *a, int n)
{
if (a == NULL)
{
return 0;
}
int i = 0;
int result = 0;
while (a[i] != NULL)
{
if (a[i] != ';')
{
result *= 10;
result += a[i]-'0';

}
i++;

}
return result;

}

char LastChar(char *a, int n)
{
int i = 0;
int j = 0;
while (a[i] != NULL)
{
j = i;
i++;
}

return a[j];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: