我的代码
ai比然与bi和bi-1的的二进制含有1的相同(有一同一)
#include <bits/stdc++.h>using namespace std;
typedef long long ll;
typedef double db;
typedef long double ldb;
typedef pair<int, int> pii;
typedef pair<ll, ll> PII;
#define pb emplace_back
//#define int ll
#define all(a) a.begin(),a.end()
#define x first
#define y second
#define ps push_back
#define endl '\n'
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)void solve();const int N = 1e6 + 10;signed main() {IOS;ll t;cin >> t;while(t--)solve();return 0;
}ll sb(ll xx){ll ans = 0;while(xx) xx >>= 1,ans ++;return ans;}
ll n;
vector<ll> a(N),b(N);void solve() {cin >> n;for(int i = 1; i <= n - 1; ++ i) { cin >> b[i]; a[i] = b[i]; }a[n] = b[n-1];for(int i = 2; i <= n; ++ i){if((a[i] & a[i-1]) == b[i-1]) continue;else{ll jie = a[i] & a[i-1];for(int k = 0; k <= max(sb(a[i]),sb(b[i-1])); ++ k){int a1 = 1 << k & a[i];int b1 = 1 << k & b[i-1];if(a1 != b1){jie += 1 << k;}}a[i] = jie;if((a[i] & a[i-1] )!= b[i-1]){cout << -1 << endl;return;}}}for(int i = 1; i <= n; ++ i) cout << a[i] << " \n"[i==n];
}
官方题解
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 5;
int n, b[MAX_N], a[MAX_N];
void solve() {cin >> n;for (int i = 1; i < n; i++)cin >> b[i];b[0] = b[n] = 0;for (int i = 1; i <= n; i++)a[i] = b[i - 1] | b[i];bool valid = true;for (int i = 1; i < n; i++)if ((a[i] & a[i + 1]) != b[i]) {valid = false;break;}if (valid) {for (int i = 1; i <= n; i++)cout << a[i] << ' ';cout << '\n';} elsecout << -1 << endl;
}
int main() {int t;cin >> t;while (t--)solve();
}