1. 程式人生 > >Codeforces Round #481 (Div. 3) D. Almost Arithmetic Progression

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

tmp res spa ssi com png true inf false

D. Almost Arithmetic Progression

技術分享圖片技術分享圖片

Example 1
input
4
24 21 14 10
output
3

Example 2
input
2
500 500
output
0

Example 3
input
5
1 3 6 9 12
output
1

題目大意:

題目大意:
你只能對3個數字選擇三個操作中的一個分別操作一次:1.-1,2:+1,3:+0
問將數組改成等差數列的最少次數

分析:

分析:
暴力枚舉操作,詳細看代碼

code:

#define debug
#include<bits/stdc++.h>
#define pb push_back
#define dbg(x) cout<<#x<<" = "<<(x)<<endl;
#define lson l,m,rt<<1
#define cmm(x) cout<<"("<<(x)<<")";
#define rson m+1,r,rt<<1|1
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll>PLL;
typedef pair<int,ll>Pil;
const ll INF = 0x3f3f3f3f;
const ll inf=0x7fffffff;
const double eps=1e-8;
const int maxn =1e6+10;
const int N = 510;
const ll mod=1e9+7;
const ll MOD=1e9;
//------
//define
ll a[maxn];
ll b[maxn];
ll sum[maxn];
ll ans=INF;
int n;
//trying
void trying(int in,int af){
	for(int i=0;i<n;i++)b[i]=a[i];
	b[0]+=in;
	b[1]+=af;
	ll sub=b[1]-b[0];
	ll tmp=abs(in)+abs(af);
	for(int i=2;i<n;i++){
		if((abs(b[i]-b[i-1]-sub))>1){
			tmp=INF;
			break;
		}
		tmp+=(abs(b[i]-b[i-1]-sub));
		b[i]=b[i-1]+sub;
	}
	ans=min(ans,tmp);
}
//solve
void solve() {
	//int n;
	while(cin>>n){
		ans=INF;
		for(int i=0;i<n;i++){
			cin>>a[i];
		}
		if(n<=2)cout<<"0"<<endl;
		else{
			for(int i=-1;i<=1;i++){
				for(int j=-1;j<=1;j++){
					trying(i,j);
				}
			}
			if(ans==INF){
				cout<<-1<<endl;
			}else{
				cout<<ans<<endl;
			}
		}
	}

}

int main() {
	ios_base::sync_with_stdio(false);
#ifdef debug
	freopen("in.txt", "r", stdin);
//	freopen("out.txt","w",stdout);
#endif
	cin.tie(0);
	cout.tie(0);
	solve();
	/*
		#ifdef debug
			fclose(stdin);
			fclose(stdout);
			system("out.txt");
		#endif
	*/
	return 0;
}

  

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