M Addition (思维)


题目链接
题意:
给定数组\(s,a,b\)\(a=\displaystyle\sum_{i=0}^{n-1} s_i*a_i*{2^i},b=\displaystyle\sum_{i=0}^{n-1} s_i*b_i*{2^i},c=\displaystyle\sum_{i=0}^{n-1} s_i*c_i*{2^i}\),求数组\(c\)使得\(c=a+b\).

思路:
求得\(sum=a+b\),对每一位二进制位分解:

  • 若当前二进制位为\(1\)\(s_i=1\),则\(c_i=1\)
  • 若当前二进制位为\(1\)\(s_i=1\),则\(c_i=-1,sum=sum+{2^{i+1}}\)

code:

#include 
using namespace std;
using ll = long long;
int a[70], b[70], c[70], s[70];

ll pows(ll a, ll b) {
    ll ret = 1;
    while(b) {
        if(b & 1) ret = ret * a;
        a = a * a;
        b >>= 1;
    }
    return ret;
}

int main() {
    int n;
    cin >> n;
    for(int i = 0; i < n; i++) cin >> s[i];
    for(int i = 0; i < n; i++) cin >> a[i];
    ll sum = 0;
    for(int i = 0; i < n; i++) {
        cin >> b[i];
        sum += (a[i] + b[i]) * s[i] * pows(2, i);
    }
    
    for(int i = 0; i < n; i++) {
        int a = (sum >> i) & 1;
        if(a){
            if(s[i] == -1){
                c[i] = 1;
                sum += pows(2, i + 1);
            }
            else c[i] = 1;
        }
        else c[i] = 0;
        if(i != 0)cout << " ";
        cout << c[i];
    }
    return 0;
}