1409C. Yet Another Array Restoration(等差数列,暴力)

C. Yet Another Array Restoration

这题考虑起来会有很多细节

但是我们注意到 n n 很小,而给出的 x , y x,y 一定在等差数列的某个位置

那我们不就枚举 x , y x,y 在数列的哪个位置吗?

这样可以算出公差,进而算出等差数列的首项和尾项

假如首项或尾项小于0就不合法,一直取 m i n min 就好了

但是在代码中,我默认公差是大于0的

因为公差小于0是一样的,只不过是公差大于0的数列倒过来而已

#include <bits/stdc++.h>
using namespace std;
int a,b,x,y;
int main()
{
	int t,n; cin >> t;
	while( t-- )
	{
		cin >> n >> x >> y;
		if( x<y )	swap(x,y);
		int ans=1e9,cha=x-y,ss,first;//???
		for(int i=1;i<=n;i++)
		for(int j=i+1;j<=n;j++)//默认大的在后面,也就是公差大于0,其实你完全可以从j=1枚举过来,一样的 
		{
			int len=j-i;
			if( cha%len!=0 )	continue;
			int w=( cha/len );
			int one=( x-(j-1)*w ),last=x+( n-j )*w;//首项和尾项 
			if( one<=0 )	continue;
			if( last>=ans )	continue;
			ans=last,first=one,ss=w;
		} 
		for(int i=1;i<=n;i++)
		{
			cout << first << " ";
			first+=ss;
		}
		cout << endl;
	}
}

猜你喜欢

转载自blog.csdn.net/jziwjxjd/article/details/108417032