<pre>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;


public class Lunch {

	static int counter;
	static int limit;
	static ArrayList&lt;Integer&gt; status;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s;
		String valuesS[];
		
		int[][] food = new int[4][];
		
		
		
			try {
				while(!((s = br.readLine()).equals(&quot;0 0 0 0 0&quot;)))
				{
					status = new ArrayList&lt;&gt;();
					counter = 0;
					limit = 0;
					valuesS = s.split(&quot; &quot;);
					limit = Integer.parseInt(valuesS[0]);
					for(int i = 0; i &lt; food.length; i++)
					{
						food[i] = new int[Integer.parseInt(valuesS[i + 1])];
					}
					
					for(int i = 0; i &lt; food.length; i++)
					{
						s = br.readLine();
						valuesS = s.split(&quot; &quot;);
						for(int j = 0; j &lt; food[i].length; j++)
						{
							food[i][j] = Integer.parseInt(valuesS[j]);
						}
					}
					
					System.out.println(&quot;Limit: &quot;+limit);
					solve(0, food, 0);
					
					System.out.println(counter);
				}
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		

	}
	
	private static void solve(int lvl, int[][]food, int currSpent)
	{
		System.out.println(status.toString());
		for(int i = 0; i &lt; food[lvl].length; i++)
		{
			if(food[lvl][i] + currSpent &lt;= limit)
			{
				if(lvl == 3)
				{
					counter++;
					System.out.println(&quot;Reseni nalezeno&quot;);
					continue;
				}
				else
				{
					//System.out.println(&quot;lvl: &quot;+ lvl);
					//System.out.println(&quot;i: &quot;+i);
					status.add(food[lvl][i]);
					solve(lvl+1, food, food[lvl][i] + currSpent);
				}
			}
			else {
				continue;
			}
		}
		
		if(status.size() != 0) status.remove(status.size() - 1);
	}

}
</pre>
