Codeforces Round #481 (Div. 3) D. Almost Arithmetic Progression

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn = 1e5 + 10;

int main()
{
    int n;
    int a[maxn];
    int ans = 1e9;

    cin >> n;
    for(int i = 0; i < n; i++)
        cin >> a[i];

    //a[0]的变化
    for(int i = -1; i <= 1; i++)
    {
        //a[1]的变化
        for(int j = -1; j <= 1; j++)
        {
            //等差数列的 等差值
            int d = (a[1]+j) - (a[0]+i);

            //a[0]是否改变,a[0]改变,i为+-1
            //cnt为改变的个数,首先就是判断a[0]是否改变
            int cnt = abs(i);

            int k;
            for(k = 1; k < n; k++)
            {
                //a[k]与以a[0]为起点的相差k个等差的值的差
                int x = abs(a[k] - (a[0]+i+k*d));
                //如果这个差x比1大,说明三种改变方案下,等差数列均不成立
                if(x > 1) break;
                //如果x为1,说明这个数需要改变,所以cnt要加
                cnt += x;
            }
            if(k == n) ans = min(ans, cnt);
        }
    }

    //ans<1e9,说明有方案成立,有解
    //ans=1e9,说明无解,输出-1
    cout << (ans < 1e9 ? ans : -1);

    return 0;
}

 

转载于:https://my.oschina.net/Userxs/blog/1812486

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值