编程之美2.14 算法实现

来源:互联网 发布:淘宝买家累计信用提升 编辑:程序博客网 时间:2024/04/30 03:11

// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<time.h>
#include<assert.h>
#include<limits.h>
#include<math.h>
#include<fstream>
#include<algorithm>
#include<float.h>
#include<vector>
using namespace std;
time_t t1,t2;
void Tic()
{
  t1=time(NULL);
 // for(int i=0;i<INT_MAX;++i);
}
void Toc()
{
   t2=time(NULL);
    std::cout<<"time:"<<(t2-t1)/3600<<"时:"<<(t2-t1)%3600/60<<"分:"<<(t2-t1)%60<<"秒"<<std::endl;
}
int RandInt(int low,int high)
{
 float temp=rand()/(static_cast<float>(RAND_MAX));
 int k=low+static_cast<int>((high-low)*temp);
 return k;
}
void PrintVector(const vector<int>&iV)
{
 for(vector<int>::const_iterator ite=iV.begin();ite!=iV.end();++ite)
 {
  std::cout<<*ite<<"  ";
 }
 std::cout<<std::endl;
}
int FindMaxSubSum(std::vector<int>&L)
{
 //求最大的子数组之和
 //L[0] 无效
 int maxSum=L[1];
 int *sum=new int[L.size()];
 L[0]=0;
 for(int i=0;i<L.size();++i)
  sum[i]=L[i];
 for(int i=1;i<L.size();++i)
 {
  if(L[i]<L[i]+sum[i-1])
   sum[i]=L[i]+sum[i-1];
  else
   sum[i]=L[i];
  if(sum[i]>maxSum)
   maxSum=sum[i];
 }
 return maxSum;
}
/
void RunAlgorithm()
{
  /*3
  6
  1 -2 3 5 -3 2
  6
  0 -2 3 5 -1 2
  6
  -9 2 -3 -5 -3*/
 std::ifstream in;
 in.open("in.txt",std::ios::in);
 int k=0;
 in>>k;
 std::vector<int>L;
    while(k)
 {
  L.clear();
  L.push_back(0);//填充一个哨岗
  int temp;
  int n=0;
  in>>n;
  while(n)
  {
   in>>temp;
   L.push_back(temp);
   n--;
  }
  std::cout<<FindMaxSubSum(L)<<std::endl;
  k--;

 }
 in.close();
 
}

int _tmain(int argc, _TCHAR* argv[])
{
 
    RunAlgorithm();
   
 system("pause");

 return 0;
}

 

原创粉丝点击