CF:A and B 数学等效思想

B. A and B

题意:给A,B两个数,通过操作:第i次操作将A或B加i。用最少的操作次数使A,B相等。
解析:
考虑等效思想,对A+i相当于对B-i。问题转化为1(+/-)2(+/-)3(+/-)…(+/-)n=A-B。大小等于等差数列 ( n + 1 ) n / 2 -(n+1)*n/2 ( n + 1 ) n / 2 (n+1)*n/2 ,n项的表达式奇偶性相等,因为改变一个数前的符合后答案加上或减去这个数的二倍。
所以从1开始枚举n,直到A-B在这个范围内并且奇偶性相等时就是答案

#include<bits/stdc++.h>
using namespace std;
void solve(){
    int a,b;
    cin>>a>>b;
    int x=max(a,b)-min(a,b);
    if(x==0) {
        cout<<"0"<<endl;
        return ;
    }
    int ans=1;
    while(1){
        long long sum=1ll*(ans+1)*ans/2;
        if(x<=sum&&sum%2==x%2){
            cout<<ans<<endl;
            return ;
        }
        ++ans;
    }
}
int main(){
    int T;
    cin>>T;
    while(T--){
        solve();
    }
}
发布了96 篇原创文章 · 获赞 11 · 访问量 2271

猜你喜欢

转载自blog.csdn.net/weixin_43769146/article/details/103722167
今日推荐