题解
发现随着 \(i\) 越大,绝对符号内的值越大,因此具有单调性,可以应用二分查找找离0最近的 \(i\)
而值可以用 等差数列求和公式 快速求出
code
#include<bits/stdc++.h>
using namespace std;
/*
mt19937_64 rnd(time(0));
#define double long double
#define lowbit(x) ((x)&(-x))
const int inf=1e18;
const int mod=1e9+7;
const int N=4e5;
int qpow(int a,int n)
{
int res=1;
while(n)
{
if(n&1) res=res*a%mod;
a=a*a%mod;
n>>=1;
}
return res;
}
int inv(int x)
{
return qpow(x,mod-2);
}
int fa[2000005];
int finds(int now) { return now == fa[now] ? now :fa[now]=finds(fa[now]); }
vector<int> G[200005];
int dfn[200005],low[200005];
int cnt=0,num=0;
int in_st[200005]={0};
stack<int> st;
int belong[200005]={0};
void scc(int now,int fa)
{
dfn[now]=++cnt;
low[now]=dfn[now];
in_st[now]=1;
st.push(now);
for(auto next:G[now])
{
if(next==fa) continue;
if(!dfn[next])
{
scc(next,now);
low[now]=min(low[now],low[next]);
}
else if(in_st[next])
{
low[now]=min(low[now],dfn[next]);
}
}
if(low[now]==dfn[now])
{
int x;
num++;
do
{
x=st.top();
st.pop();
in_st[x]=0;
belong[x]=num;
}while(x!=now);
}
}
vector<int> prime;
bool mark[200005]={0};
void shai()
{
for(int i=2;i<=200000;i++)
{
if(!mark[i]) prime.push_back(i);
for(auto it:prime)
{
if(it*i>200000) break;
mark[it*i]=1;
if(it%i==0) break;
}
}
}
*/
#define int long long
int cal(int n,int k,int i)
{
int add=(k+k+i-1)*i/2;
int jian=(k+i+k+n-1)*(n-i)/2;
return add-jian;
}
void solve()
{
int n,k;
cin>>n>>k;
int l=0,r=n+1;
while(l+1<r)
{
int mid=(l+r)/2;
if(cal(n,k,mid)>=0) r=mid;
else l=mid;
}
cout<<min(abs(cal(n,k,l)),abs(cal(n,k,r)))<<'\n';
}
signed main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int TT=1;
cin>>TT;
while(TT--) solve();
return 0;
}
标签:200005,int,DUPER,st,LARGE,next,low,Array,now
From: https://www.cnblogs.com/pure4knowledge/p/18404284