CS302 Midterm, Fall, 2014

James S. Plank

Answers and Grading


Question 1: 14 points

This is an interesting example of crowd-sourcing: The class majority got 100%:

abcdefghijklmnopqrstuvwxyz
A100060000004256300200000000
B000724000003542020000000000
C0251111044110142110000000000
D1011237400002183032100000000
E010044880000038030000000000
F001103003001602130000000000
G000000001000010216791013780
H000813001001581020000000000
I0000000000011100213723003141
J0100123000000354100100000000
K000513101021591100000000000
L000024000015021035700000000
M01001113000004830151100000000
N2400004100400031010010000000


Question 2: 17 points


Question 3: 15 points

abcdefghijklmnopqrstuvwxyz
A0000000000023000000005432110
B058000901100100000221000000
C232011218124003100011113000001
D1100000001110232182911000471
E1903115130084024302101000102


Question 4: 14 points

Push the value to the end of h and percolate up:

void PQueue::Push(double d)
{
  int index, p;

  h.push_back(d);
  index = h.size()-1;
  while (1) {
    if (index == 0) return;
    p = (index - 1) / 2;
    if (h[p] <= h[index]) return;
    h[index] = h[p];
    h[p] = d;
    index = p;
  }
}

Grading:


Question 5: 19 points

Outline your solution in English: This is going to be a power set enumeration. I want to enumerate all subsets of N. Each subset that I enumerate will represent the number of red balls, and the elements not in the subset will represent the number of blue balls. I'll calculate those values, and if they equal r and b, then I return 1. If I reach the end of the enumeration without finding r and b, I'll return 0. It would save some time were I to total up the elements of N and making sure that it equals r+b before bothering with the enumeration. You didn't have to do that.

With 20 elements which can each be 199,999,999, these sums can exceed the maximum value of an integer. For that reason, your sums should be long long's, rather than integers.

N's size: A power set enumeration of N elements is O(2N). You start reaching the 2 second limit in Topcoder at about 222.

Here's an implementation with a main(): (in q5.cpp)

#include <vector>
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

int RB(int r, int b, vector <int> &N)
{
  long long R, B;
  int i, j;

  R = 0;
  for (i = 0; i < N.size(); i++) R += N[i];
  if (R != r + b) return 0;

  for (i = 0; i < (1 << N.size()); i++) {
    R = 0;
    B = 0;
    for (j = 0; j < N.size(); j++) {
      if (i & (1 << j)) {
        R += N[j];
      } else {
        B += N[j];
      }
    }
    if (R == r && B == b) return 1;
  }
  return 0;
}

main()
{
  int r, b, i;
  vector <int> N;

  cin >> r >> b;
  while (cin >> i) N.push_back(i);
  printf("%d\n", RB(r, b, N));
  exit(0);
}

Grading: