acwing周赛140 b题

acwing周赛140 b题_第1张图片

思路:我们按照从小到大的顺序将数组逆转好,然后枚举数组首项,分别让其+1,-1,+0,然后求出公差,从前往后遍历即可。

代码:

int ans1(){//不动
	int cha = (a[n] - a[1] + 1) / (n - 1);
	int t = a[1];
	int cnt = 0;
	for(int i = 2;i <= n;i ++){
		t += cha;
		if(abs(t - a[i]) > 1)
			return 0x3f3f3f3f;
		if(t != a[i])
			cnt ++;
	}
	return cnt;
}

int ans2(){//+1
	int cha = (a[n] - a[1]) / (n - 1);
	int t = a[1] + 1;
	int cnt = 1;
	for(int i = 2;i <= n;i ++){
		t += cha;
		if(abs(t - a[i]) > 1)
			return 0x3f3f3f3f;
		if(t != a[i])
			cnt ++;
	}
	return cnt;
}

int ans3(){//-1
	int cha = (a[n] - a[1] + 2) / (n - 1);
	int t = a[1] - 1;
	int cnt = 1;
	for(int i = 2;i <= n;i ++){
		t += cha;
		if(abs(t - a[i]) > 1)
			return 0x3f3f3f3f;
		if(t != a[i])
			cnt ++;
	}
	return cnt;
}

void solve(){
	cin >> n;
	vectorb(n + 1);
	for(int i = 1;i <= n;i ++)
		cin >> a[i], b[i] = a[i];
	sort(b.begin() + 1,b.end());
	if(a[1] > a[n])reverse(a + 1,a + 1 + n);
	if(n <= 2){
		cout << 0;
		return;
	}
	int ans = min({ans1(),ans2(),ans3()});
	if(b[1] == b[n])ans = 0;
	if(ans > n)
		cout << -1;
	else
		cout << ans;
}

你可能感兴趣的:(算法,数据结构)