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;
    }
  • 相关阅读:
    python web 框架的基本逻辑练习题
    jQuery 自定义方法(扩展方法)
    jQuery 的动画效果图片----隐藏打开方法
    jQuery 小练习-拖拉画面
    用jQuery来绑定事件的3种方法和区别
    css用hover制作下拉菜单
    巧用hover改变css样式和背景
    mpvue中按需引入echarts
    webpack配置css浏览器前缀
    Vue中使用Sass全局变量
  • 原文地址:https://www.cnblogs.com/zzqc/p/6693107.html
Copyright © 2011-2022 走看看