Boolean Game - CodeChef Solution in Java| AskTheCode
- Team ATC
- Apr 11, 2021
- 5 min read
Updated: Apr 12, 2021
CodeChef April Long Challenge Solution | Boolean Game (BOOLGAME) solution | AskTheCode
Problem:
Consider N binary variables x1,x2,…,xN. For each valid i, the i-th of these variables can be xi=0 or xi=1; therefore, there are 2N possible assignments of values to the variables. For each valid i, setting xi=1 gives you score gi.
In addition, there are M special intervals (numbered 1 through M). For each valid i, the i-th interval is [ui,vi] and if xui=xui+1=…=xvi=1, then your score increases by di.
Note that both gi and di can be negative (setting more variables to 1 can decrease your score), and your score can also be negative. Formally, the score of an assignment of values to the binary variables is

Find the K highest scores among all assignments on these variables. Formally, if we computed the scores of all 2N assignments and sorted them in non-increasing order, you should find the first K of these values.
Input:
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains three space-separated integers N, M and K.
The second line contains N space-separated integers g1,g2,…,gN.
M lines follow. For each valid i, the i-th of these lines contains three space-separated integers ui, vi and di.
Output:
For each test case, print a single line containing K space-separated integers ― the K highest scores of assignments on the binary variables, in decreasing order.
Example Input:
1 4 2 3 -4 -2 5 2 1 3 0 1 4 -3
Example Output:
7 5 5
Explanation:
Example case 1: The best assignment is x=(0,0,1,1), with score 7. The second and third best assignments are (0,0,1,0) and (0,1,1,1), each with score 5.
Code:
In Java
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
/* Name of the class has to be "Main" only if the class is public. */
class Solution
{
static class Reader{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader(){
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException{
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException{
if (din == null)
return;
din.close();
}
}
static long power(long x, long y, long p){
long res = 1;
x = x % p;
while (y > 0) {
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static class Orientation implements Comparable<Orientation>{
public long score;
public long orient;
public Orientation(long score, long orient){
this.score = score;
this.orient = orient;
}
public static Orientation of (long score, long orient){
return new Orientation(score, orient);
}
@Override
public int compareTo(Orientation b){
return b.score > this.score ? 1 : -1;
}
}
public static PriorityQueue<Orientation> withPq(Orientation o){
PriorityQueue<Orientation> pq = new PriorityQueue<>();
pq.add(o);
return pq;
}
public static void main (String[] args) throws java.lang.Exception{
Reader r = new Reader();
int t = r.nextInt();
StringBuffer ans = new StringBuffer("");
long M = 1000000007;
while(t-- > 0){
int n = r.nextInt(), m = r.nextInt(), k = r.nextInt();
long []g = new long[n + 1];
long []intScore = new long[m];
Map<Integer, List<Integer>> intervals = new HashMap<>();
for (int i=1;i<=n;i++) {
g[i] = r.nextLong();
intervals.put(i, new ArrayList<>());
}
for (int i=0;i<m;i++) {
int u = r.nextInt(), v = r.nextInt(), d = r.nextInt();
intScore[i] = d;
intervals.get(u).add(i);
intervals.get(v).add(i);
}
Map<Integer, PriorityQueue<Orientation>> dp = new HashMap<>();
dp.put(0, withPq(Orientation.of(0,0)));
for (int i=1;i<=n;i++) {
PriorityQueue<Orientation> temp = new PriorityQueue<>(dp.get(i - 1));
long cur = 0, mask = 0;
Set<Integer> activeIntervals = new HashSet<>();
for (int j=i;j>=1;j--) {
cur += g[j];
mask = mask ^ (1<<j);
for (int interval : intervals.get(j)) {
if (activeIntervals.contains(interval))
cur += intScore[interval];
else
activeIntervals.add(interval);
}
if (j>1)
for (Orientation o : dp.get(j-2))
temp.add(Orientation.of(o.score + cur, o.orient ^ mask));
else
temp.add(Orientation.of(cur, mask));
}
PriorityQueue<Orientation>pq = new PriorityQueue<>();
Set<Long>selection = new HashSet<>();
while(!temp.isEmpty()) {
if (selection.size() >= k) break;
selection.add(temp.peek().score);
pq.add(temp.poll());
}
dp.put(i, pq);
}
for (int i=0;i<k;i++)
ans.append(dp.get(n).poll().score + " ");
ans.append("\n");
}
OutputStream out = new BufferedOutputStream(System.out);
out.write(String.valueOf(ans).getBytes());
out.flush();
}
}
In C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main(){
ll testcase;
cin >> testcase;
while(testcase--){
ll n, m, k_Val;
cin >> n >> m >> k_Val;
vector<ll> g(n+1);
for (ll i = 0; i < n; i++)
cin >> g[i+1];
vector<vector<pair<ll, ll>>> m_Arr(n+1), dynamic(n+1);
for (ll i = 0; i < m; i++){
ll uVal, vVal, dVal;
cin >> uVal >> vVal >> dVal;
m_Arr[uVal].push_back(make_pair(i,dVal));
m_Arr[vVal].push_back(make_pair(i, dVal));
}
dynamic[0].push_back(make_pair(0,0));
for (ll i = 1; i <= n; i++){
vector<pair<ll, ll>> tmp;
tmp.insert(tmp.end(), dynamic[i-1].begin(), dynamic[i-1].end());
ll cur_idx = 0, tmp_idx = 0;
set<ll> set1;
for (ll j = i; j >= 1; j--){
cur_idx += g[j];
tmp_idx ^= 1LL << j;
for (auto alpha:m_Arr[j]){
if (set1.count(alpha.first)){
cur_idx += alpha.second;
}
else{
set1.insert(alpha.first);
}
}
if(j > 1){
for (auto alpha:dynamic[j-2])
tmp.push_back(make_pair(alpha.first+cur_idx, tmp_idx^alpha.second));
}
else{
tmp.push_back(make_pair(cur_idx, tmp_idx));
}
}
sort(tmp.begin(), tmp.end());
reverse(tmp.begin(), tmp.end());
set<ll> set2;
ll filled = 0;
for (ll j = 0; j < tmp.size() && filled < k_Val; j++){
if (set2.count(tmp[j].second)){
continue;
}
dynamic[i].push_back(tmp[j]);
filled++;
set2.insert(tmp[j].second);
}
}
for (ll i = 0; i < k_Val; i++)
cout << dynamic[n][i].first << " ";
cout << endl;
}
return 0;
}
Comments