B. Sum of Two Numbers - 贪心+思维+构造

发布时间 2023-04-26 18:38:00作者: Yaowww

题意:

  给定一个整数n,输出x,y满足以下要求:

  1. x+y=n

  2. x的每一位上的数加在一起的数位和和y的数位和相差不超过1.

分析:

  从高位开始依次遍历,将其平均分给x和y,奇数剩余的1由x和y轮流加上。

代码:

#include <bits/stdc++.h>

#define endl '\n'

using namespace std;

typedef pair<int,int> pii;
typedef long long ll;

void solve()
{
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        ll x=0;
        ll y=0;
        int flag=0;
        for(int i=0;i<s.size();i++)
        {
            int res=s[i]-'0';
            if(res%2==0)
            {
                x+=res/2;
                y+=res/2;
            }
            else
            {
                int tt=res/2;
                x+=tt;
                y+=tt;
                if(flag==0)
                {
                    x++;
                    flag=1;
                }
                else
                {
                    y++;
                    flag=0;
                }
            }
            if(i!=s.size()-1)
            {
                x*=10;
                y*=10;
            }
        }
        cout<<x<<' '<<y<<'\n';
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
    solve();
}