Codeforces Round 971 (Div. 4)E. Klee‘s SUPER DUPER LARGE Array!!!

Klee 有一个长度为 n的数组 a ,其中按顺序包含整数 [k,k+1,...,k+n−1]。克利希望选择一个索引( 1≤i≤n),使得 x=|a1+a2+⋯+ai−ai+1−⋯−an|最小。请注意,对于任意整数 z而言, |z|表示 z的绝对值。
输出 x 的最小值。
输入

第一行包含 t( 1≤t≤10^4) - 测试用例数。
每个测试用例包含两个整数 n和 k( 2≤n,k≤10^9)--数组的长度和数组的起始元素。
输出

对于每个测试用例,另起一行输出 x 的最小值。
Example
Input
4
2 2
7 2
5 3
1000000000 1000000000
Output
1
5
1
347369930

前言:当时D题没思路先做到E题,感觉是个等差数列,推了会公式,写出代码过了样例就交了,感觉可以过,结果。。。

放一眼错误代码吧

#include<bits/stdc++.h>
using namespace std;
 
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<long long,long long> PLL;
typedef unordered_map<int,int> HashII;
typedef unordered_map<char,int> HashCI;
typedef priority_queue<int,vector<int>,greater<int>> heap;
typedef unsigned long long ULL;
typedef unordered_map<string,int> HashSI;
const int INF=0x3f3f3f3f;
const int N=2e5+10;
string s;
int n;
void solve()
{
	//---Dijkstra
	LL n,k;
	cin>>n>>k;
	LL ans = INF;
	if(n % 2 == 0){
		LL sum1 = n/2 * n/2;
		//cout<<sum1<<"\n";
		LL x = k+n/2;
		//cout<<x;
		while(sum1>abs(sum1-2*x))
		{
			sum1-=2*x;
			x++;
		}
		//cout<<sum1<<"\n";
		ans = abs(sum1);
	}
	else
	{
		LL sum2 = ((2*k+3*(n-1)/2+1)*(n-1))/4-((2*k+(n-1)/2)*(n+1))/4;
		//cout<<sum2;
		LL x = k+(n-1)/2+1;
		while(sum2>abs(sum2-2*x)){
			sum2-=2*x;
			x++;
		}
		ans = abs(sum2);
	}
	cout<<ans<<"\n";
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr),cout.tie(nullptr);
	int t ;
	cin>>t;
	while(t--)
	{
		solve();
	}
	return 0;
}

废话少说,我之所以超时的原因是没注意到n,k的数据范围是0-1e9 超时是在所难免的
简单概括一下题目就是要求求前缀和后缀的最小差值,而且是具有单调性的,所以我们可以通过二分来做,(当然数学方法也是ok的)
当我们二分查找到差值最小的l时候,此时两者差值为正数,我们需要在计算一下l+1,因为负数我们也要考虑到

#include<bits/stdc++.h>
using namespace std;
 
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<long long,long long> PLL;
typedef unordered_map<int,int> HashII;
typedef unordered_map<char,int> HashCI;
typedef priority_queue<int,vector<int>,greater<int>> heap;
typedef unsigned long long ULL;
typedef unordered_map<string,int> HashSI;
const int INF=0x3f3f3f3f;
const int N=2e5+10;
#define x first
#define y second
void solve()
{
	//---Dijkstra
	LL n,k;
	cin>>n>>k;
	LL sum = n*(k+k+n-1)>>1;//序列的总和
	LL ans = sum;
	int l = 0, r = n;
	while(l<r){//while(l<=r) 会死循环
		LL mid = (l+r+1)>>1;//当n为奇数的时候我们向上取整
		LL sum1 = mid*(2*k+mid-1)>>1;//左段序列的总和
		if(sum1<=sum-sum1) l = mid;
		else r = mid-1;
	}
	for(auto x : {l,l+1})
	{
		if(x>n) continue;
		LL sum2 = x*(k+k+x-1)>>1; 
		 ans = min((LL)ans,abs(sum2-(sum-sum2)));
	}
	cout<<ans<<"\n";
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr),cout.tie(nullptr);
	int t ;
	cin>>t;
	while(t--)
	{
		solve();
	}
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值