zoukankan      html  css  js  c++  java
  • cf188C(最大子段和&&思维)

    C. Functions again
    time limit per test
    1 second
    memory limit per test
    256 megabytes
    input
    standard input
    output
    standard output

    Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:

    In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of land r for the given array a.

    Input

    The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a.

    The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements.

    Output

    Print the only integer — the maximum value of f.

    Examples
    input
    5
    1 4 2 3 1
    output
    3
    input
    4
    1 5 4 7
    output
    6
    Note

    In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].

    In the second case maximal value of f is reachable only on the whole array.

     类似于最大循环字段和,不难发现最大子段和出现的情况分为两种:

    1  +-+-+-...

    2  -+-+-+...(此时一定不是从第一个数开始的所以将第一个数也置负即可)

    所以只要更改+-求两次最大子段取最大值就ok

    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    #define inf 0x7fffffff
    LL a[100005];
    LL LLS(int n)
    {
    	LL sumn=0,maxn=-inf,i;
    	//cout<<"ssss:"<<maxn<<endl;
    	for(i=1;i<=n;++i){
    		sumn+=a[i];
    		maxn=max(maxn,sumn);
    		if(sumn<0) sumn=0;
    	}
    	return maxn;
    }
    int main()
    {
    	LL n,i,j;
    	while(cin>>n){
    		for(i=1;i<=n;++i){
    			scanf("%lld",&a[i]);
    			if(i==1) continue;
    		a[i-1]=abs(a[i-1]-a[i]);
    		}
    		//for(i=1;i<n;++i) cout<<a[i]<<" ";
    		for(i=2;i<=n;i+=2) a[i]=-a[i];
    		j=LLS(n-1);
    
    		for(i=1;i<=n-1;++i) a[i]=-a[i];
    		cout<<max(j,LLS(n-1))<<endl;
    	}
    	return 0;
    }
  • 相关阅读:
    IOS编程之通讯录
    和iPhone有关的视图控制器:UIViewController、UITabBarController、UINavigationController及其混合用法
    跟大家分享下今天所学到的PHP,虽然很基础,但是感觉也很重要
    直接拿来用!最火的iOS开源项目
    ios各种手势,很有意思
    IOS中Json解析的四种方法
    [iOS]深入浅出 iOS 之多线程 NSThread
    IOS应用程序升级
    ios学习笔记之block在ios开发中的应用
    【热门收藏】iOS开发人员必看的精品资料(100个)——下载目录
  • 原文地址:https://www.cnblogs.com/zzqc/p/6693107.html
Copyright © 2011-2022 走看看