Almost Arithmetic Progression (Thinking, Violence CodeForces 978D)

Title Portal

Topic: To give you an array, you can +1, -1 once for each element in the array, or do not operate, ask if you can make this array into an arithmetic sequence, if possible, please print the minimum number of operations, if Cannot print -1.

1≤n≤100000

Idea: The arithmetic sequence has a tolerance. We can enumerate the first two numbers, a total of 9 operations. After the first two numbers are determined, the tolerance of this sequence is determined, and then we traverse from 3 to see if each number The legality can be achieved through operation or non-operation, and the minimum value can be maintained.

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
const int inf=0x7fffffff;
const int mod=1e9+7;
const int eps=1e-6;
typedef long long ll;
typedef unsigned long long ull;
#define ls p<<1
#define rs p<<1|1
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl '\n'
#define null NULL
int a[N],b[N];
signed main()
{
    IOS;
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        b[i]=a[i];
    }
    if(n<=2)
    {
        cout<<0<<endl;
        return 0;
    }
    int res=inf;
    for(int i=a[1]-1;i<=a[1]+1;i++)
    {
        for(int j=a[2]-1;j<=a[2]+1;j++)
        {
            int d=j-i;int cnt=0;
            if(i!=a[1])
                cnt++;
            if(j!=a[2])
                cnt++;
            for(int k=3;k<=n;k++)
            {
                int p=a[k-1];
                if(k==3)
                    p=j;
                if(abs(p+d-a[k])<=1)
                {
                    if(p+d-a[k]!=0)
                        cnt++;
                    a[k]=p+d;
                }
                else
                {
                    cnt=inf;
                    break;
                }
            }
            res=min(res,cnt);
            for(int k=3;k<=n;k++)
            {
                a[k]=b[k];
            }
        }
    }
    if(res==inf)
    {
        cout<<-1<<endl;
    }
    else
    {
        cout<<res<<endl;
    }
}
Published 93 original articles · won praise 9 · views 4203

Guess you like

Origin blog.csdn.net/Joker_He/article/details/105441165