/* Solution to Topcoder SRM 699, D1, 250-pointer */ /* James S. Plank */ /* October 6, 2016 */ #include #include #include #include using namespace std; class OthersXor { public: long long minSum(vector x); }; long long OthersXor::minSum(vector x) { bool U; int T; vector W; // These are the integers W vector Wbit; // These will be the bits of row i of W. vector A; int R; int B; int Best_B; // We keep track of the best B for each row. int i, j; long long two_to_the_i; long long RV; RV = 0; two_to_the_i = 1; /* First, calculate U and the W's */ U = false; for (i = 0; i < x.size(); i++) { if (x[i] == -1) { U = true; } else { W.push_back(x[i]); } } /* Next, concentrate on each bit individually */ for (i = 0; i < 32; i++) { /* Grab the bits of W */ Wbit.clear(); for (j = 0; j < W.size(); j++) { if (W[j] & (1 << i)) { Wbit.push_back(1); } else { Wbit.push_back(0); } } /* Sentinelize Best_B */ Best_B = 500; /* Do as in the writeup. First calculate A, then R, then B, for each setting of T */ for (T = 0; T < 2; T++) { printf("W:"); for (j = 0; j < Wbit.size(); j++) printf(" %d", Wbit[j]); /* Here, we calculate A. */ A.clear(); for (j = 0; j < Wbit.size(); j++) A.push_back(T ^ Wbit[j]); printf(" A:"); for (j = 0; j < Wbit.size(); j++) printf(" %d", A[j]); /* Now R and B */ R = T; B = 0; for (j = 0; j < Wbit.size(); j++) { R ^= A[j]; B += A[j]; } B += R; /* Check to see if B is legal, and if so check it against Best_B */ if (R == 1 && U == false) { /* The answer is illegal */ } else if (B < Best_B) { Best_B = B; } printf(" R:%d i:%d T:%d B:%d\n", R, i, T, B); } /* If none of the B's were legal, then return -1 */ if (Best_B == 500) return -1; /* Otherwise, add B times 2^i to RV */ RV += (two_to_the_i * Best_B); two_to_the_i <<= 1; } return RV; }