Cyclic Sequence_Maximum Subsegments and Variants

First time blogging....
An icpc trial water question..
The main idea of ​​the title: Give you a cyclic sequence of integers, that is, a sequence connected head to tail, and ask to find the largest sub-segment sum (in the sense of loop)
That is, the largest subsection and question often asked for, but this time the array is connected head to tail

 
Idea 1: The usual method is to copy this integer array and connect it to the back of the original array, so that it becomes the maximum subsection and problem with upper and lower limits, and the problem- solving method is to consult the relevant information.

Idea 2: We can think in another way. To find the maximum field sum, we can first solve the maximum sub-segment sum in the sense of the cycle through the ans-minimum sub-segment, and this minimum sub-segment is excluding the first and last elements. The smallest consecutive sub-segment (this achieves the meaning of the cycle) , in addition, the largest sub-segment sum is used to find another situation , so that the two are compared, and the largest is the largest sub-segment sum of the cyclic sequence.

On my code:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100005],n;

int maxsum() //normally find the maximum continuous subsection sum
{
 int res,tmp;
 res=tmp=a[0];
 for(int j=1;j<n;j++)
 {
  if(tmp<0)
  tmp= a[j];
  else
  tmp+=a[j];
  
  res=max(res,tmp);
 }
 return res;
 
}
int minsum()
{
 if(n<=2)
 return 0;//If the number of elements in the array is less than 2, return
 
 int directly res,tmp;
 res=tmp=a[1];
 //Remove the first and last nodes to find out which The minimum subsection of and otherwise have the same meaning as maxsum
 for(int j=2;j<n-1;j++)
 {
  if(tmp>0)
  tmp=a[j];
  else
  tmp+=a[j];
  
  res =min(res,tmp);
  }
 
  return res;
 }

int main()
{
 int tt=0,ans;
 scanf("%d",&n);
 for(int i=0;i<n;i++)
 {
 scanf("%d",&a[i]);
 tt+=a[i];}
 
 /*int k1=maxsum();
 int k2=minsum();
 printf("**%d %d\n",k1,k2);*/
 
 ans=max(maxsum(),tt-minsum());
 printf("%d\n",ans);
 return 0;
 
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325933998&siteId=291194637