Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
- #define F(i, n) for(int i = 0; i < n; i++)
- using ll = long long;
- using vi = vector<int>;
- using pii = pair<int, int>;
- const int LIMIT_INT = 1e5+5, LIMIT_LLONG = 1e9+5;
- const long long MOD = 1e9+7;
- int tests, n;
- void solve()
- {
- cin>>n;
- vi rocks(n);
- int high_odd = -1, high_even = -1;
- F(i, n) {
- cin>>rocks[i];
- if(i > 0 && i < (n - 1)) {
- if(rocks[i] % 2 && rocks[i] > 1) high_odd = i;
- else if(rocks[i] % 2 == 0 && rocks[i] > 1) high_even = i;
- }
- }
- if(n == 3) {
- if(rocks[1] % 2) cout<<"-1\n";
- else cout<<rocks[1] / 2<<"\n";
- } else if(rocks[n - 2] == 1 && high_odd == -1 && high_even == -1) {
- cout<<"-1\n";
- }
- else {
- int last_odd = -1;
- int last_even = -1;
- ll op = 0;
- if(rocks[n - 2] == 1) {
- if(high_even > -1) rocks[high_even] -= 2;
- else if(high_odd > -1) rocks[high_odd] -= 2;
- op++;
- rocks[n - 2] = 2;
- }
- for(int i = n - 2; i >= 1; i--) {
- if(rocks[i] % 2) {
- if(last_even == -1 && last_odd == -1) last_odd = i;
- else if(last_odd > -1) {
- rocks[i]--;
- rocks[last_odd]--;
- op += 2;
- last_even = last_odd;
- last_odd = -1;
- } else if(last_even > -1) {
- rocks[i]++;
- rocks[last_even] -= 2;
- op++;
- last_even = i;
- }
- } else {
- if(last_odd > -1) {
- rocks[i] -= 2;
- rocks[last_odd]++;
- op++;
- last_even = last_odd;
- last_odd = -1;
- } else last_even = i;
- }
- }
- for(int i = n - 2; i >= 1; i--) {
- op += (rocks[i] / 2);
- }
- cout<<op<<"\n";
- }
- }
- int main() {
- fast_io;
- cin>>tests;
- while(tests--) solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement