Problem:
Problem G: Oil Company

Irving & Cohen Petroleum Corporation has decided to develop a new oil field in an area. A preliminary survey
has been done and they created a detailed grid map of the area which indicates the reserve of oil.

They are now planning to construct mining plants on several grid blocks according this map, but they decided
not to place any two plants on adjacent positions to avoid spreading of fire in case of blaze. Two blocks are
considered to be adjacent when they have a common edge. You are one of the programmers working for the
company and your task is to write a program which calculates the maximum amount of oil they can mine, given
the map of the reserve.

Input

The first line of the input specifies N, the number of test cases. Then N test cases follow, each of which looks
like the following:

W H
r1,1 r2,1 . . . rW,1
...
r1,H r2,H . . . rW,H

The first line of a test case contains two integers W and H (1 ≤ W, H ≤ 20). They specifies the dimension of
the area. The next H lines, each of which contains W integers, represent the map of the area. Each integer rx,y
(0 ≤ rx,y < 10000) indicates the oil reserve at the grid block (x, y).

Output

For each test case, output the case number (starting from 1) and the maximum possible amount of mining in a
line. Refer to the sample output section about the format.

Sample Input

2
2 2
2 3
3 5
3 2
4 1 1
2 1 4

Output for the Sample Input

Case 1: 7
Case 2: 8

Solution in JAVA (judge verdict: Time Limit Exceeded)

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

//Oil Company
public class Main{

	@SuppressWarnings("unchecked")
	void run(){
		Set<Integer>[] valid = new Set[21];
		for(int L=1;L<=20;L++){
			valid[L] = new HashSet<Integer>();
			for(int S=0;S<1<<L;S++){
				boolean ok = true;
				for(int j=0;j+1<L;j++)if(((S>>j)&1)>0 && ((S>>(j+1))&1)>0)ok = false;
				if(ok)valid[L].add(S);
			}
		}
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		int[][] dp = new int[2][1<<20];
		for(int CASE=1;CASE<=T;CASE++){
			int w = sc.nextInt(), h = sc.nextInt();
			int[][] a = new int[h][w];
			for(int i=0;i<h;i++)for(int j=0;j<w;j++)a[i][j]=sc.nextInt();
			int mask = (1<<w)-1, x = 0, bit = 1<<(w-1);
			for(int[]d:dp)Arrays.fill(d, 0);
			for(int i=0;i<h;i++)for(int j=0;j<w;j++,x=1-x){
				Arrays.fill(dp[x], 0);
				for(int S:valid[w]){
					int ns = (S<<1)&mask;
					dp[x][ns] = Math.max(dp[x][ns], dp[1-x][S]);
					if((S&bit)==0 && (j==0||(S&1)==0))dp[x][ns|1] = Math.max(dp[x][ns|1], dp[1-x][S]+a[i][j]);
					else dp[x][ns] = Math.max(dp[x][ns], dp[1-x][S]);
				}
			}
			int res = 0;
			for(int S:valid[w])res = Math.max(res, dp[1-x][S]);
			System.out.println("Case "+CASE+": "+res);
		}
	}
	
	public static void main(String[] args) {
		new Main().run();
	}
}