//package round203;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;

public class B {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int[] a = na(n);
		int[] b = na(n);
		int[] f = new int[n];
		for(int i = 0;i < n;i++){
			if(b[i] != 0){
				f[b[i]-1]++;
			}
		}

		Queue<Integer> q = new ArrayDeque<Integer>();
		int[] d = new int[n];
		Arrays.fill(d, 99999999);
		for(int i = 0;i < n;i++){
			if(a[i] == 1){
				q.add(i);
				d[i] = 0;
			}
		}
		int[] prev = new int[n];
		Arrays.fill(prev, -1);

		while(!q.isEmpty()){
			int cur = q.poll();
			if(b[cur] != 0){
				int nex = b[cur]-1;
				if(a[nex] == 0 && f[nex] == 1 && d[nex] > d[cur] + 1){
					d[nex] = d[cur] + 1;
					prev[nex] = cur;
					q.add(nex);
				}
			}
		}

		int max = -1;
		int maxi = -1;
		for(int i = 0;i < n;i++){
			if(d[i] < 99999999 && d[i] > max){
				max = d[i];
				maxi = i;
			}
		}

		out.println(max+1);
		StringBuilder sb = new StringBuilder();
		for(;;maxi = prev[maxi]){
			sb.append(" " + (maxi+1));
			if(a[maxi] == 1)break;
		}
		out.println(sb.substring(1));
	}
	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new B().run(); }

	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.util.*;
import java.io.*;
import java.math.*;

public class A {
    int P[];
    int T[];
    int dp[];
    int degIn[];
    int mark[];
    void solve() {
        int n = sc.nextInt();
        P = new int[n + 1];
        T = new int[n + 1];
        degIn = new int[n + 1];
        mark = new int[n + 1];
        dp = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            T[i] = sc.nextInt();
        }
        for (int i = 1; i <= n; i++) {
            P[i] = sc.nextInt();
            degIn[P[i]]++;
        }
        int mx = -1;
        int mxI = -1;
        for (int i = 1; i <= n; i++) {
            dfs(i);
            if (T[i] == 1 && dp[i] > mx) {
                mx = dp[i];
                mxI = i;
            }
        }
        int l = 0;
        int ans[] = new int[n];
        int v = mxI;
        while( !(v == 0 || degIn[v] > 1) ) {
            ans[l++] = v;
            v = P[v];
        }
        out.println(mx);
        while(l-- > 0) {
            out.print(ans[l] + " ");
        }
    }
    int dfs(int v) {
        if (v == 0 || degIn[v] > 1) {
            dp[v] = 0;
            return 0;
        }
        if (mark[v] == 1) {
            return dp[v];
        }
        mark[v] = 1;
        dp[v] = dfs(P[v]) + 1;
        return dp[v];
    }

    FastScanner sc;
    PrintWriter out;

    public static void main(String[] args) {
        (new A()).run();
    }

    void run() {
        sc = new FastScanner();
        out = new PrintWriter(System.out);
        solve();
        out.flush();
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(String s) {
            try {
                br = new BufferedReader(new FileReader(s));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public FastScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String nextToken() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(nextToken());
        }

        long nextLong() {
            return Long.parseLong(nextToken());
        }

        double nextDouble() {
            return Double.parseDouble(nextToken());
        }

        String nextStr() {
            return nextToken();
        }
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Stack;

/**
 * Works good for CF
 * @author cykeltillsalu
 */
public class B {

	//some local config
	static boolean test = false;
	static String testDataFile = "testdata.txt";
	static String feedFile = "feed.txt";
	CompetitionType type = CompetitionType.CF;
	private static String ENDL = "\n";

	// solution
	private void solve() throws Throwable {

		int n = iread();
		boolean[] isHotel = new boolean[n];
		for (int i = 0; i < n; i++) {
			isHotel[i] = iread() == 1;
		}

		int[] path = new int[n];
		int[] fromcnt = new int[n];
		for (int i = 0; i < n; i++) {
			int pathFrom = iread()-1;
			if(pathFrom == -1){
				path[i] = -1;
				continue;
			}
			fromcnt[pathFrom] ++;
			path[i] = pathFrom;
		}

		Stack<Integer> ret = new Stack();
		for (int start = 0; start < n; start++) {

			if(isHotel[start]){
				Stack<Integer> ans = new Stack();
				ans.push(start);
				int cur = path[start];
				while(cur >= 0 && fromcnt[cur] == 1){
					ans.push(cur);
					cur = path[cur];
				}
				if(ans.size() > ret.size()){
					ret = ans;
				}
			}
		}

		out.write(ret.size() + "\n");
		while(ret.size() > 0){
			out.write((ret.pop()+1) + " ");
		}
		out.write("\n");

		out.flush();
	}

	public int iread() throws Exception {
		return Integer.parseInt(wread());
	}

	public double dread() throws Exception {
		return Double.parseDouble(wread());
	}

	public long lread() throws Exception {
		return Long.parseLong(wread());
	}

	public String wread() throws IOException {
		StringBuilder b = new StringBuilder();
		int c;
		c = in.read();
		while (c >= 0 && c <= ' ')
			c = in.read();
		if (c < 0)
			return "";
		while (c > ' ') {
			b.append((char) c);
			c = in.read();
		}
		return b.toString();
	}

	public static void main(String[] args) throws Throwable {

		if(test){ //run all cases from testfile:
			BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile));
			String readLine = testdataReader.readLine();
			int casenr = 0;
			out: while (true) {
				BufferedWriter w = new BufferedWriter(new FileWriter(feedFile));
				if(!readLine.equalsIgnoreCase("input")){
					break;
				}
				while (true) {
					readLine = testdataReader.readLine();
					if(readLine.equalsIgnoreCase("output")){
						break;
					}
					w.write(readLine + "\n");
				}
				w.close();
				System.out.println("Answer on case "+(++casenr)+": ");

				new B().solve();
				System.out.println("Expected answer: ");

				while (true) {
					readLine = testdataReader.readLine();

					if(readLine == null){
						break out;
					}
					if(readLine.equalsIgnoreCase("input")){
						break;
					}
					System.out.println(readLine);
				}
				System.out.println("----------------");
			}
			testdataReader.close();
		} else { // run on server
			new B().solve();
		}
		out.close();
	}

	public B() throws Throwable {
		if (test) {
			in = new BufferedReader(new FileReader(new File(feedFile)));
		}
	}

	InputStreamReader inp = new InputStreamReader(System.in);
	BufferedReader in = new BufferedReader(inp);
	static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

	enum CompetitionType {CF, OTHER};
}


import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class B
{
        String line;
        StringTokenizer inputParser;
        BufferedReader is;
        FileInputStream fstream;
        DataInputStream in;
        String FInput="";

        void openInput(String file)
        {

                if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
                else
                {
                        try{

                        fstream = new FileInputStream(file);
                        in = new DataInputStream(fstream);
                        is = new BufferedReader(new InputStreamReader(in));
                        }catch(Exception e)
                        {
                                System.err.println(e);
                        }
                }

        }

        void readNextLine()
    	{
    		try {
    			line = is.readLine();
    			inputParser = new StringTokenizer(line, " ,\t");
    			//System.err.println("Input: " + line);
    		} catch (IOException e) {
    			System.err.println("Unexpected IO ERROR: " + e);
    		}
    		catch (NullPointerException e)
    		{
    			line=null;

    		}

    	}

        long NextLong()
        {
                String n = inputParser.nextToken();

                long val = Long.parseLong(n);

                 return val;
        }

        int NextInt()
        {
                String n = inputParser.nextToken();
                int val = Integer.parseInt(n);

                //System.out.println("I read this number: " + val);
                return val;
        }

        String NextString()
        {
                String n = inputParser.nextToken();
                return n;
        }

        void closeInput()
        {
                try {
                        is.close();
                } catch (IOException e) {
                        System.err.println("Unexpected IO ERROR: " + e);
                }

        }

        public static void main(String [] argv)
        {
                //String filePath="circles.in";
                String filePath=null;
                if(argv.length>0)filePath=argv[0];
                new B(filePath);

        }

        public B(String inputFile)
        {
        	openInput(inputFile);
    		StringBuilder sb = new StringBuilder();
    		readNextLine();
        	int N=100000;//NextInt();
        	boolean [] h = new boolean[N];
        	int [] p = new int[N];
        	readNextLine();
        	for(int i=0; i<N; i++)
        	{
        		h[i]=false;//(NextInt()==1);
        	}
        	h[N-1]=true;
        	readNextLine();
        	for(int i=0; i<N; i++)
        		p[i]=-2;
        	for(int i=0; i<N; i++)
        	{
        		int a=i-1;//NextInt()-1;
        		if(a<0)continue;
        		if(p[a]==-2)
        		{
        			p[a]=i;
        		}
        		else p[a]=-1;
        	}
        	int max=0;

        	int [] u = new int[N];
        	for(int i=0; i<N; i++)
        	{
        		if(u[i]>0)continue;
        		boolean [] u2 = new boolean[N];
        		int len=1;
        		int x=i;
        		StringBuilder ss=new StringBuilder();
        		ss.append((x+1)+" ");
        		while(p[x]>=0&&!u2[p[x]]&&u[x]<=len)
        		{
        			x=p[x];
        			u2[x]=true;
        			u[x]=Math.max(u[x], len);
        			ss.append((x+1)+" ");
        			len++;
        		}
        		if((!h[x]))continue;
        		if(len>max)
        		{
        			max=len;
        			ss.insert(0, len+"\n");
        			sb=ss;
        		}
        	}
        	System.out.println(sb);
    		closeInput();

        }

}


import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class B
{
        String line;
        StringTokenizer inputParser;
        BufferedReader is;
        FileInputStream fstream;
        DataInputStream in;
        String FInput="";

        void openInput(String file)
        {

                if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
                else
                {
                        try{

                        fstream = new FileInputStream(file);
                        in = new DataInputStream(fstream);
                        is = new BufferedReader(new InputStreamReader(in));
                        }catch(Exception e)
                        {
                                System.err.println(e);
                        }
                }

        }

        void readNextLine()
    	{
    		try {
    			line = is.readLine();
    			inputParser = new StringTokenizer(line, " ,\t");
    			//System.err.println("Input: " + line);
    		} catch (IOException e) {
    			System.err.println("Unexpected IO ERROR: " + e);
    		}
    		catch (NullPointerException e)
    		{
    			line=null;

    		}

    	}

        long NextLong()
        {
                String n = inputParser.nextToken();

                long val = Long.parseLong(n);

                 return val;
        }

        int NextInt()
        {
                String n = inputParser.nextToken();
                int val = Integer.parseInt(n);

                //System.out.println("I read this number: " + val);
                return val;
        }

        String NextString()
        {
                String n = inputParser.nextToken();
                return n;
        }

        void closeInput()
        {
                try {
                        is.close();
                } catch (IOException e) {
                        System.err.println("Unexpected IO ERROR: " + e);
                }

        }

        public static void main(String [] argv)
        {
                //String filePath="circles.in";
                String filePath=null;
                if(argv.length>0)filePath=argv[0];
                new B(filePath);

        }

        public B(String inputFile)
        {
        	openInput(inputFile);
    		StringBuilder sb = new StringBuilder();
    		readNextLine();
        	int N=NextInt();
        	boolean [] h = new boolean[N];
        	int [] p = new int[N];
        	readNextLine();
        	for(int i=0; i<N; i++)
        	{
        		h[i]=(NextInt()==1);
        	}
        	readNextLine();
        	for(int i=0; i<N; i++)
        		p[i]=-2;
        	for(int i=0; i<N; i++)
        	{
        		int a=NextInt()-1;
        		if(a<0)continue;
        		if(p[a]==-2)
        		{
        			p[a]=i;
        		}
        		else p[a]=-1;
        	}
        	int max=0;

        	boolean [] u = new boolean[N];
        	for(int i=0; i<N; i++)
        	{
        		if(u[i])continue;
        		int len=1;
        		int x=i;
        		StringBuilder ss=new StringBuilder();
        		ss.append((x+1)+" ");
        		while(p[x]>=0)
        		{
        			x=p[x];
        			u[x]=true;
        			ss.append((x+1)+" ");
        			len++;
        		}
        		if((!h[x]))continue;
        		if(len>max)
        		{
        			max=len;
        			ss.insert(0, len+"\n");
        			sb=ss;
        		}
        	}
        	System.out.println(sb);
    		closeInput();

        }

}


import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class B
{
        String line;
        StringTokenizer inputParser;
        BufferedReader is;
        FileInputStream fstream;
        DataInputStream in;
        String FInput="";

        void openInput(String file)
        {

                if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
                else
                {
                        try{

                        fstream = new FileInputStream(file);
                        in = new DataInputStream(fstream);
                        is = new BufferedReader(new InputStreamReader(in));
                        }catch(Exception e)
                        {
                                System.err.println(e);
                        }
                }

        }

        void readNextLine()
    	{
    		try {
    			line = is.readLine();
    			inputParser = new StringTokenizer(line, " ,\t");
    			//System.err.println("Input: " + line);
    		} catch (IOException e) {
    			System.err.println("Unexpected IO ERROR: " + e);
    		}
    		catch (NullPointerException e)
    		{
    			line=null;

    		}

    	}

        long NextLong()
        {
                String n = inputParser.nextToken();

                long val = Long.parseLong(n);

                 return val;
        }

        int NextInt()
        {
                String n = inputParser.nextToken();
                int val = Integer.parseInt(n);

                //System.out.println("I read this number: " + val);
                return val;
        }

        String NextString()
        {
                String n = inputParser.nextToken();
                return n;
        }

        void closeInput()
        {
                try {
                        is.close();
                } catch (IOException e) {
                        System.err.println("Unexpected IO ERROR: " + e);
                }

        }

        public static void main(String [] argv)
        {
                //String filePath="circles.in";
                String filePath=null;
                if(argv.length>0)filePath=argv[0];
                new B(filePath);

        }

        public B(String inputFile)
        {
        	openInput(inputFile);
    		StringBuilder sb = new StringBuilder();
    		readNextLine();
        	int N=NextInt();
        	boolean [] h = new boolean[N];
        	int [] p = new int[N];
        	readNextLine();
        	for(int i=0; i<N; i++)
        	{
        		h[i]=(NextInt()==1);
        	}
        	h[N-1]=true;
        	readNextLine();
        	for(int i=0; i<N; i++)
        		p[i]=-2;
        	for(int i=0; i<N; i++)
        	{
        		int a=NextInt()-1;
        		if(a<0)continue;
        		if(p[a]==-2)
        		{
        			p[a]=i;
        		}
        		else p[a]=-1;
        	}
        	int max=0;

        	int [] u = new int[N];
        	for(int i=0; i<N; i++)
        	{
        		if(u[i]>0)continue;
        		boolean [] u2 = new boolean[N];
        		int len=1;
        		int x=i;
        		StringBuilder ss=new StringBuilder();
        		ss.append((x+1)+" ");
        		while(p[x]>=0&&!u2[p[x]]&&u[x]<=len)
        		{
        			x=p[x];
        			u2[x]=true;
        			u[x]=Math.max(u[x], len);
        			ss.append((x+1)+" ");
        			len++;
        		}
        		if((!h[x]))continue;
        		if(len>max)
        		{
        			max=len;
        			ss.insert(0, len+"\n");
        			sb=ss;
        		}
        	}
        	System.out.println(sb);
    		closeInput();

        }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class B {

	public static void main(String[] args) throws IOException{
		Scanner sc = new Scanner(System.in);

		final int n = sc.nextInt();
		boolean[] is_hotel = new boolean[n];
		int[] from = new int[n];

		LinkedList<Integer> list = new LinkedList<Integer>();

		for(int i = 0; i < n; i++){
			is_hotel[i] = sc.nextInt() == 1;
			if(is_hotel[i]){
				list.add(i);
			}
		}

		for(int i = 0; i < n; i++){
			from[i] = sc.nextInt() - 1;
		}

		int[] count = new int[n];
		for(int i = 0; i < n; i++){
			if(from[i] < 0){
				continue;
			}

			count[from[i]]++;
		}

		LinkedList<Integer> answer = new LinkedList<Integer>();
		LinkedList<Integer> current = new LinkedList<Integer>();

		for(int start : list){
			int cur = start;
			current.add(cur);
			while(from[cur] >= 0 && count[from[cur]] < 2){
				cur = from[cur];
				current.addFirst(cur);
			}

			if(answer.size() < current.size()){
				LinkedList<Integer> tmp = answer;
				answer = current;
				current = tmp;
			}
			current.clear();
		}

		System.out.println(answer.size());
		boolean first = true;
		for(int pos : answer){
			if(!first){
				System.out.print(" ");
			}else{
				first = false;
			}
			System.out.print(pos + 1);
		}
		System.out.println();

	}

	public static class Scanner {

		private BufferedReader br;
		private StringTokenizer tok;

		public Scanner(InputStream is) throws IOException{
			br = new BufferedReader(new InputStreamReader(is));
			getLine();
		}

		private void getLine() throws IOException{
			while(tok == null || !tok.hasMoreTokens()){
				tok = new StringTokenizer(br.readLine());
			}
		}

		private boolean hasNext(){
			return tok.hasMoreTokens();
		}

		public String next() throws IOException{
			if(hasNext()){
				return tok.nextToken();
			}else{
				getLine();
				return tok.nextToken();
			}
		}

		public int nextInt() throws IOException{
			if(hasNext()){
				return Integer.parseInt(tok.nextToken());
			}else{
				getLine();
				return Integer.parseInt(tok.nextToken());
			}
		}

		public long nextLong() throws IOException{
			if(hasNext()){
				return Long.parseLong(tok.nextToken());
			}else{
				getLine();
				return Long.parseLong(tok.nextToken());
			}
		}

		public double nextDouble() throws IOException{
			if(hasNext()){
				return Double.parseDouble(tok.nextToken());
			}else{
				getLine();
				return Double.parseDouble(tok.nextToken());
			}
		}
	}
}


/**
 * @author Juan Sebastian Beltran Rojas
 * @mail jsbeltran.valhalla@gmail.com
 * @veredict No enviado
 * @problemId 350B
 * @problemName Resort
 * @judge http://www.codeforces.com
 * @category graph
 * @level easy
 * @date Oct 1, 2013
 **/
import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Math.*;
public class CF350B {
	public static void main(String args[]) throws Throwable {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int N=parseInt(in.readLine().trim());
		boolean hotels[]=new boolean[N];
		StringTokenizer st=new StringTokenizer(in.readLine());
		for(int i=0;i<N;i++)
			hotels[i]=parseInt(st.nextToken())==1;
		st=new StringTokenizer(in.readLine());
		ArrayList<Integer> lAdy[]=new ArrayList[N];
		ArrayList<Integer> lAdySol[]=new ArrayList[N];
		for(int i=0;i<N;i++)
			lAdySol[i]=new ArrayList<Integer>();
		int[] cant=new int[N];
		for(int i=0;i<N;i++) {
			lAdy[i]=new ArrayList<Integer>();
			int v=parseInt(st.nextToken());
			if(v>0) {
				lAdy[i].add(v-1);
				lAdySol[v-1].add(i);
				cant[v-1]++;
			}
		}
		int max=0,sol=-1;
		int[][] cola=new int[N][2];
		for(int i=0;i<N;i++) {
			int p=0,c=0;
			if(hotels[i]) {
				cola[c][0]=i;
				cola[c++][1]=1;
				for(;p<c;) {
					int[] n=cola[p++];
					if(n[1]>max) {
						max=n[1];
						sol=n[0];
					}
					for(int a:lAdy[n[0]])
						if(cant[a]==1) {
							cola[c][0]=a;
							cola[c++][1]=n[1]+1;
						}
				}
			}
		}
		sb.append(max).append("\n");
		for(;!hotels[sol];sol=lAdySol[sol].get(0))
			sb.append(sol+1).append(" ");
		sb.append(sol+1).append("\n");
		System.out.print(new String(sb));
	}
}


import java.util.*;

public class cf350B{

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] hotel = new int[n+1];
		int[] adj = new int[n+1];
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();

		for(int i=0; i<n; i++)
		 hotel[i+1] = sc.nextInt();

		for(int i=1; i<=n; i++)
		{
			adj[i] = sc.nextInt();
			if(hm.get(adj[i]) != null)
				hm.put(adj[i],-1);
			else
				hm.put(adj[i],0);
		}

		boolean[] visited = new boolean[n];
		ArrayList<Integer> path = new ArrayList<Integer>();
		ArrayList<Integer> temp_path = new ArrayList<Integer>();
		int path_size = 0, max_size = -1000000000;
		for(int i=1; i<=n; i++)
		{
			if(hotel[i] == 1)
			{
				path_size =0;
				int j=i;
				temp_path = new ArrayList<Integer>();

				while(j!=0)
				{
					temp_path.add(0,j);
					j = adj[j];
					path_size++;
					if(hm.get(j) == -1)
						break;
				}

				if(path_size > max_size)
				{
					max_size = path_size;
					path = temp_path;
				}

			}

		}

		System.out.println(max_size);
		for(int p : path)
		{
			System.out.print(p+" ");

		}
		System.out.println();

	}

}


import java.util.*;

public class cf350B{

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] hotel = new int[n+1];
		int[] adj = new int[n+1];
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		ArrayList<Integer> hotels = new ArrayList<Integer>();
		for(int i=1; i<=n; i++)
		{
		 int this_val = sc.nextInt();
		 if(this_val == 1)
		 		hotels.add(i);
		}

		for(int i=1; i<=n; i++)
		{
			adj[i] = sc.nextInt();
			if(hm.get(adj[i]) != null)
				hm.put(adj[i],-1);
			else
				hm.put(adj[i],0);
		}

		int[] dp = new int[n+1];
		ArrayList<Integer> path = new ArrayList<Integer>();
		ArrayList<Integer> temp_path = new ArrayList<Integer>();
		int path_size = 0, max_size = -1000000000;

			for(int i: hotels)
			{
				path_size =0;
				int j=i;
				temp_path = new ArrayList<Integer>();

				path_size = find_path(dp, i, temp_path,adj,hm );

				if(path_size > max_size)
				{
					max_size = path_size;
					path = temp_path;
				}

			}

		System.out.println(max_size);
		for(int p : path)
		{
			System.out.print(p+" ");

		}
		System.out.println();

	}

	public static int find_path(int[] dp, int end, ArrayList<Integer> temp_path,int[] adj, HashMap<Integer, Integer> hm )
	{
		int j= end;
		if(end == 0)
			return 0;

		if(hm.get(j)!= null && hm.get(j) == -1)
			return 0;
		if(dp[end] != 0)
			return dp[end];

		temp_path.add(0,j);
		int prev_j = j;
		j = adj[j];
		dp[prev_j] = find_path(dp, j, temp_path, adj, hm)+1;
		return dp[prev_j];

	}

}


import java.util.*;

public class cf350B{

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] hotel = new int[n+1];
		int[] adj = new int[n+1];
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		ArrayList<Integer> hotels = new ArrayList<Integer>();
		for(int i=1; i<=n; i++)
		{
		 int this_val = sc.nextInt();
		 if(this_val == 1)
		 		hotels.add(i);
		}

		for(int i=1; i<=n; i++)
		{
			adj[i] = sc.nextInt();
			if(hm.get(adj[i]) != null)
				hm.put(adj[i],-1);
			else
				hm.put(adj[i],0);
		}

		int[] dp = new int[n+1];
		ArrayList<Integer> path = new ArrayList<Integer>();
		ArrayList<Integer> temp_path = new ArrayList<Integer>();
		int path_size = 0, max_size = -1000000000;

			for(int i: hotels)
			{
				path_size =0;
				int j=i;
				temp_path = new ArrayList<Integer>();

				path_size = find_path(dp, i, temp_path,adj,hm );

				if(path_size > max_size)
				{
					max_size = path_size;
					path = temp_path;
				}

			}

		System.out.println(max_size);
		for(int p : path)
		{
			System.out.print(p+" ");

		}
		System.out.println();

	}

	public static int find_path(int[] dp, int end, ArrayList<Integer> temp_path,int[] adj, HashMap<Integer, Integer> hm )
	{
		int j= end;
		if(end == 0)
			return 0;

		if(hm.get(j)!= null && hm.get(j) == -1)
			return 0;
		if(dp[end] != 0)
			return dp[end];

		int prev_j = j;
		j = adj[j];
		dp[prev_j] = find_path(dp, j, temp_path, adj, hm)+1;
		temp_path.add(prev_j);
		return dp[prev_j];

	}

}


import java.util.*;

public class cf350B{

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] hotel = new int[n+1];
		int[] adj = new int[n+1];
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		ArrayList<Integer> hotels = new ArrayList<Integer>();
		for(int i=1; i<=n; i++)
		{
		 int this_val = sc.nextInt();
		 if(this_val == 1)
		 		hotels.add(i);
		}

		for(int i=1; i<=n; i++)
		{
			adj[i] = sc.nextInt();
			if(hm.get(adj[i]) != null)
				hm.put(adj[i],-1);
			else
				hm.put(adj[i],0);
		}

		ArrayList<Integer> path = new ArrayList<Integer>();
		ArrayList<Integer> temp_path = new ArrayList<Integer>();
		int path_size = 0, max_size = -1000000000;

			for(int i: hotels)
			{
				path_size =0;
				int j=i;
				temp_path = new ArrayList<Integer>();

				while(j!=0)
				{
					temp_path.add(0,j);
					j = adj[j];
					path_size++;
					if(hm.get(j) == -1)
						break;
				}

				if(path_size > max_size)
				{
					max_size = path_size;
					path = temp_path;
				}

			}

		System.out.println(max_size);
		for(int p : path)
		{
			System.out.print(p+" ");

		}
		System.out.println();

	}

}


import java.util.Arrays;
import java.util.Scanner;

public class B {

    /**
     * @param args
     */
    static int startvertex;
    static boolean flag=false;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        int[] mountains = new int[n];
        int hotel=0;
        int counter = 0;
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            if (a[i] == 0)
                mountains[counter++] = i;
            else
                hotel = i;
        }
        int[] indexes = new int[n];
        int[] b = new int[n];

        Arrays.fill(indexes, -1);
        for (int i = 0; i < n; i++) {
            b[i] = sc.nextInt() - 1;
            if (b[i] != -1) {
                if (indexes[b[i]] == -1)
                    indexes[b[i]] = i;
                else
                    indexes[b[i]] = -2;
            }
        }
        int[] res = new int[n];
        int max = 0;
        int index = -1;
        for (int i = 0; i < counter; i++) {
            if (indexes[mountains[i]] >= 0) {
                startvertex = mountains[i];
                int t = solve(res, a, indexes, mountains[i]);
                if (t > max) {
                    max = t;
                    index = i;
                }
            }
        }
        if (max == 0) {
            System.out.println(1);
            System.out.println(hotel+1);
        } else {
            System.out.println(max);
            int k = 1;
            index = mountains[index];
            System.out.print(index + 1);

            while (k != max) {
                index = indexes[index];
                System.out.print(" " + (index + 1));
                k++;
            }
        }
    }

    static int solve(int res[], int[] a, int[] indexes, int vertex) {
        if (indexes[vertex]==startvertex||flag){
            res[vertex]=-2;
            flag = false;
            return -1;
        }
        if (res[vertex] == 0) {
            if (indexes[vertex] < 0) {
                if (indexes[vertex] == -1 && a[vertex] == 1) {// hotel
                    res[vertex] = 1;
                    return 1;
                } else {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                }
            } else {
                int t = solve(res, a, indexes, indexes[vertex]);
                if (t < 0) {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                } else {
                    res[vertex] = t + 1;
                    return t + 1;
                }
            }

        } else
            return res[vertex];
    }

}


import java.util.Arrays;
import java.util.Scanner;

public class B {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        int[] mountains = new int[n];
        int hotel=0;
        int counter = 0;
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            if (a[i] == 0)
                mountains[counter++] = i;
            else
                hotel = i;
        }
        int[] indexes = new int[n];
        int[] b = new int[n];

        Arrays.fill(indexes, -1);
        for (int i = 0; i < n; i++) {
            b[i] = sc.nextInt() - 1;
            if (b[i] != -1) {
                if (indexes[b[i]] == -1)
                    indexes[b[i]] = i;
                else
                    indexes[b[i]] = -2;
            }
        }
        int[] res = new int[n];
        int max = 0;
        int index = -1;
        for (int i = 0; i < counter; i++) {
            if (indexes[mountains[i]] >= 0) {
                int t = solve(res, a, indexes, mountains[i]);
                if (t > max) {
                    max = t;
                    index = i;
                }
            }
        }
        if (max == 0) {
            System.out.println(1);
            System.out.println(hotel+1);
        } else {
            System.out.println(max);
            int k = 1;
            index = mountains[index];
            System.out.print(index + 1);

            while (k != max) {
                index = indexes[index];
                System.out.print(" " + (index + 1));
                k++;
            }
        }
    }

    static int solve(int res[], int[] a, int[] indexes, int vertex) {
        if (vertex<0)
            {
                return -1;
            }
        if (res[vertex] == 0) {
            if (indexes[vertex] < 0) {
                if (indexes[vertex] == -1 && a[vertex] == 1) {// hotel
                    res[vertex] = 1;
                    return 1;
                } else {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                }
            } else {
                int t = solve(res, a, indexes, indexes[vertex]);
                if (t < 0) {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                } else {
                    res[vertex] = t + 1;
                    return t + 1;
                }
            }

        } else
            return res[vertex];
    }

}


import java.util.Arrays;
import java.util.Scanner;

public class B {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        int[] mountains = new int[n];
        int hotel=0;
        int counter = 0;
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            if (a[i] == 0)
                mountains[counter++] = i;
            else
                hotel = i;
        }
        int[] indexes = new int[n];
        int[] b = new int[n];

        Arrays.fill(indexes, -1);
        for (int i = 0; i < n; i++) {
            b[i] = sc.nextInt() - 1;
            if (b[i] != -1) {
                if (indexes[b[i]] == -1)
                    indexes[b[i]] = i;
                else
                    indexes[b[i]] = -2;
            }
        }
        int[] res = new int[n];
        int max = 0;
        int index = -1;
        for (int i = 0; i < counter; i++) {
            if (indexes[mountains[i]] >= 0) {
                int t = solve(res, a, indexes, mountains[i]);
                if (t > max) {
                    max = t;
                    index = i;
                }
            }
        }
        if (max == 0) {
            System.out.println(1);
            System.out.println(hotel+1);
        } else {
            System.out.println(max);
            int k = 1;
            index = mountains[index];
            System.out.print(index + 1);

            while (k != max) {
                index = indexes[index];
                System.out.print(" " + (index + 1));
                k++;
            }
        }
    }

    static int solve(int res[], int[] a, int[] indexes, int vertex) {
        if (res[vertex] == 0) {
            if (indexes[vertex] < 0) {
                if (indexes[vertex] == -1 && a[vertex] == 1) {// hotel
                    res[vertex] = 1;
                    return 1;
                } else {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                }
            } else {
                int t = solve(res, a, indexes, indexes[vertex]);
                if (t < 0) {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                } else {
                    res[vertex] = t + 1;
                    return t + 1;
                }
            }

        } else
            return res[vertex];
    }

}


import java.util.Arrays;
import java.util.Scanner;

public class B {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        int[] mountains = new int[n];
        int hotel=0;
        int counter = 0;
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            if (a[i] == 0)
                mountains[counter++] = i;
            else
                hotel = i;
        }
        int[] indexes = new int[n];
        int[] b = new int[n];

        Arrays.fill(indexes, -1);
        for (int i = 0; i < n; i++) {
            b[i] = sc.nextInt() - 1;
            if (b[i] != -1) {
                if (indexes[b[i]] == -1)
                    indexes[b[i]] = i;
                else
                    indexes[b[i]] = -2;
            }
        }
        int[] res = new int[n];
        int max = 0;
        int index = -1;
        for (int i = 0; i < counter; i++) {
            if (indexes[mountains[i]] >= 0) {
                int t = solve(res, a, indexes, mountains[i]);
                if (t > max) {
                    max = t;
                    index = i;
                }
            }
        }
        if (max == 0) {
            System.out.println(1);
            System.out.println(hotel+1);
        } else {
            try{
            System.out.println(max);
            int k = 1;
            index = mountains[index];
            System.out.print(index + 1);

            while (k != max) {
                index = indexes[index];
                System.out.print(" " + (index + 1));
                k++;
            }
            }
            catch(Exception e){}
        }
    }

    static int solve(int res[], int[] a, int[] indexes, int vertex) {
        if (res[vertex] == 0) {
            if (indexes[vertex] < 0) {
                if (indexes[vertex] == -1 && a[vertex] == 1) {// hotel
                    res[vertex] = 1;
                    return 1;
                } else {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                }
            } else {
                int t = solve(res, a, indexes, indexes[vertex]);
                if (t < 0) {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                } else {
                    res[vertex] = t + 1;
                    return t + 1;
                }
            }

        } else
            return res[vertex];
    }

}


import java.util.Arrays;
import java.util.Scanner;

public class B {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        int[] mountains = new int[n];
        int hotel=0;
        int counter = 0;
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            if (a[i] == 0)
                mountains[counter++] = i;
            else
                hotel = i;
        }
        int[] indexes = new int[n];
        int[] b = new int[n];

        Arrays.fill(indexes, -1);
        for (int i = 0; i < n; i++) {
            b[i] = sc.nextInt() - 1;
            if (b[i] != -1) {
                if (indexes[b[i]] == -1)
                    indexes[b[i]] = i;
                else
                    indexes[b[i]] = -2;
            }
        }
        int[] res = new int[n];
        int max = 0;
        int index = -1;
        for (int i = 0; i < counter; i++) {
            if (indexes[mountains[i]] > 0) {
                int t = solve(res, a, indexes, mountains[i]);
                if (t > max) {
                    max = t;
                    index = i;
                }
            }
        }
        if (max == 0) {
            System.out.println(1);
            System.out.println(hotel+1);
        } else {
            System.out.println(max);
            int k = 1;
            index = mountains[index];
            System.out.print(index + 1);

            while (k != max) {
                index = indexes[index];
                System.out.print(" " + (index + 1));
                k++;
            }
        }
    }

    static int solve(int res[], int[] a, int[] indexes, int vertex) {
        if (res[vertex] == 0) {
            if (indexes[vertex] < 0) {
                if (indexes[vertex] == -1 && a[vertex] == 1) {// hotel
                    res[vertex] = 1;
                    return 1;
                } else {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                }
            } else {
                int t = solve(res, a, indexes, indexes[vertex]);
                if (t < 0) {
                    res[vertex] = -1;
                    indexes[vertex] = -2;
                    return -1;
                } else {
                    res[vertex] = t + 1;
                    return t + 1;
                }
            }

        } else
            return res[vertex];
    }

}


import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.awt.Point;
import java.math.BigInteger;

import static java.lang.Math.*;

public class Codeforces_Solution_B implements Runnable{

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException{
        if (ONLINE_JUDGE){
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }else{
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException{
        while(!tok.hasMoreTokens()){
            try{
                tok = new StringTokenizer(in.readLine());
            }catch (Exception e){
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException{
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException{
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException{
        return Double.parseDouble(readString());
    }

    public static void main(String[] args){
        new Thread(null, new Codeforces_Solution_B(), "", 128 * (1L << 20)).start();
    }

    long timeBegin, timeEnd;

    void time(){
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory(){
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB");
    }

    void debug(Object... objects){
        if (DEBUG){
            for (Object o: objects){
                System.err.println(o.toString());
            }
        }
    }

    public void run(){
        try{
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            time();
            memory();
        }catch (Exception e){
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    boolean DEBUG = false;

       void solve() throws IOException{

          int n = readInt();

          int[] type = new int[n];
          int[] a = new int[n];
          int[] count = new int[n];
          int[] d = new int[n];
          Arrays.fill(d, -1);

          for (int i=0; i<n; i++) type[i] = readInt();

          for (int i=0; i<n; i++) {
              a[i] = readInt()-1;

              if (a[i]>-1) count[a[i]]++;

          }

          int k = 0;
          ArrayList<Integer> ans = new ArrayList<Integer>();

          for (int i=0; i<n; i++) {
              if (type[i]==1) {
                  int t = i;
                  int temp=0;

                  ArrayList<Integer> thisAns = new ArrayList<Integer>();

                  while (t!=-1) {
                      thisAns.add(t);
                      t = a[t];
                      temp++;
                      if (t==-1 || count[t]!=1) break;
                  }

                  if (temp>k) {
                      k = temp;
                      ans = (ArrayList<Integer>) thisAns.clone();
                  }

              }
          }

          Collections.reverse(ans);

          out.println(k);
          for (int x : ans) out.print((x+1)+" ");

   }

}


import java.util.*;
import java.io.*;
/*
 * author:yanghui
 */
public class B {

	class InputReader {

		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream));
			tokenizer = null;
		}

		public InputReader() throws FileNotFoundException {
			reader = new BufferedReader(new FileReader("d:/input.txt"));
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

	}

	boolean visit[];

	public class point{
		ArrayList<Integer> next ;
		int cur;
		public point (int cur){
			this.cur = cur;
			next = new ArrayList<Integer>();
		}
	}

	point p[] ;
	int num[] = new int[500010];

	public void addedge(int u , int v){
		p[v].next.add(u);
		num[u] ++;
	}

	List<Integer> ans = new ArrayList<Integer>();
	List<Integer> tcur = new ArrayList<Integer>();

	public void dfs(int v){
		if(p[v].next.size() == 1 && num[p[v].next.get(0)] == 1){
			tcur.add(v);
			dfs(p[v].next.get(0));
		}else{
			tcur.add(v);
			int len = tcur.size();
			if(len > ans.size()){
				ans.clear();
				ans.addAll(tcur);
				tcur.clear();
			}
		}
	}

	public void run() {

		InputReader reader = new InputReader(System.in);
		int n = reader.nextInt();
		int type[] = new int[n+1];
		for(int i = 1 ; i <= n ; i ++)
			type[i] = reader.nextInt();
		int a[] = new int[n+1];
		visit = new boolean[n+1];
		Arrays.fill(visit, false);
		p = new point[n+1];
		for(int i = 1 ; i <= n ; i ++){
			p[i] = new point(i);
		}
		for(int i = 1 ; i <= n ; i ++){
			a[i] = reader.nextInt();
			if(a[i] != 0)
				addedge(a[i],i);
		}
		for(int i = 1 ; i <= n ; i ++){
			if(type[i] == 1){
				dfs(i);
			}
		}
		System.out.println(ans.size());
		for(int i = ans.size() - 1 ; i >= 0 ; i --){
			System.out.print(ans.get(i));
			if(i != 0)
				System.out.print(" ");
			else
				System.out.println();
		}

	}

	public static void main(String args[]) {
		new B().run();
	}
}


import java.util.*;
import java.io.*;
/*
 * author:yanghui
 */
public class B {

	class InputReader {

		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream));
			tokenizer = null;
		}

		public InputReader() throws FileNotFoundException {
			reader = new BufferedReader(new FileReader("d:/input.txt"));
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

	}

	boolean visit[];

	public class point{
		ArrayList<Integer> next ;
		int cur;
		public point (int cur){
			this.cur = cur;
			next = new ArrayList<Integer>();
		}
	}

	point p[] ;
	int num[] = new int[500010];

	public void addedge(int u , int v){
		p[v].next.add(u);
		num[u] ++;
	}

	List<Integer> ans = new ArrayList<Integer>();
	List<Integer> tcur = new ArrayList<Integer>();

	public void dfs(int v){
		if(p[v].next.size() == 1 && num[p[v].next.get(0)] == 1 && type[p[v].next.get(0)] == 0){
			tcur.add(v);
			dfs(p[v].next.get(0));
		}else{
			tcur.add(v);
			int len = tcur.size();
			if(len > ans.size()){
				ans.clear();
				ans.addAll(tcur);
				tcur.clear();
			}
		}
	}
	int type[];

	public void run() {

		InputReader reader = new InputReader(System.in);
		int n = reader.nextInt();
		type = new int[n+1];
		for(int i = 1 ; i <= n ; i ++)
			type[i] = reader.nextInt();
		int a[] = new int[n+1];
		visit = new boolean[n+1];
		Arrays.fill(visit, false);
		p = new point[n+1];
		for(int i = 1 ; i <= n ; i ++){
			p[i] = new point(i);
		}
		for(int i = 1 ; i <= n ; i ++){
			a[i] = reader.nextInt();
			if(a[i] != 0)
				addedge(a[i],i);
		}
		for(int i = 1 ; i <= n ; i ++){
			if(type[i] == 1){
				dfs(i);
			}
		}
		System.out.println(ans.size());
		for(int i = ans.size() - 1 ; i >= 0 ; i --){
			System.out.print(ans.get(i));
			if(i != 0)
				System.out.print(" ");
			else
				System.out.println();
		}

	}

	public static void main(String args[]) {
		new B().run();
	}
}


import java.util.*;
import java.io.*;
/*
 * author:yanghui
 */
public class B {

	class InputReader {

		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream));
			tokenizer = null;
		}

		public InputReader() throws FileNotFoundException {
			reader = new BufferedReader(new FileReader("d:/input.txt"));
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

	}

	boolean visit[];

	public class point{
		ArrayList<Integer> next ;
		int cur;
		public point (int cur){
			this.cur = cur;
			next = new ArrayList<Integer>();
		}
	}

	point p[] ;
	int num[] = new int[500010];

	public void addedge(int u , int v){
		p[v].next.add(u);
		num[u] ++;
	}

	List<Integer> ans = new ArrayList<Integer>();
	List<Integer> tcur = new ArrayList<Integer>();

	public void dfs(int v){
		if(p[v].next.size() == 1 && num[p[v].next.get(0)] == 1 && type[p[v].next.get(0)] == 0){
			System.out.println(v);
			dfs(p[v].next.get(0));
		}else{
			tcur.add(v);
			int len = tcur.size();
			if(len > ans.size()){
				ans.clear();
				ans.addAll(tcur);
				tcur.clear();
			}
		}
	}
	int type[];

	public void run() {

		InputReader reader = new InputReader(System.in);
		int n = reader.nextInt();
		type = new int[n+1];
		for(int i = 1 ; i <= n ; i ++)
			type[i] = reader.nextInt();
		int a[] = new int[n+1];
		visit = new boolean[n+1];
		Arrays.fill(visit, false);
		p = new point[n+1];
		for(int i = 1 ; i <= n ; i ++){
			p[i] = new point(i);
		}
		for(int i = 1 ; i <= n ; i ++){
			a[i] = reader.nextInt();
			if(a[i] != 0)
				addedge(a[i],i);
		}
		for(int i = 1 ; i <= n ; i ++){
			if(type[i] == 1){
				tcur.clear();
				dfs(i);
			}
		}
		System.out.println(ans.size());
		for(int i = ans.size() - 1 ; i >= 0 ; i --){
			System.out.print(ans.get(i));
			if(i != 0)
				System.out.print(" ");
			else
				System.out.println();
		}

	}

	public static void main(String args[]) {
		new B().run();
	}
}


import java.util.*;
import java.io.*;
/*
 * author:yanghui
 */
public class B {

	class InputReader {

		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			reader = new BufferedReader(new InputStreamReader(stream));
			tokenizer = null;
		}

		public InputReader() throws FileNotFoundException {
			reader = new BufferedReader(new FileReader("d:/input.txt"));
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

	}

	boolean visit[];

	public class point{
		ArrayList<Integer> next ;
		int cur;
		public point (int cur){
			this.cur = cur;
			next = new ArrayList<Integer>();
		}
	}

	point p[] ;
	int num[] = new int[500010];

	public void addedge(int u , int v){
		p[v].next.add(u);
		num[u] ++;
	}

	List<Integer> ans = new ArrayList<Integer>();
	List<Integer> tcur = new ArrayList<Integer>();

	public void dfs(int v){
		if(p[v].next.size() == 1 && num[p[v].next.get(0)] == 1 && type[p[v].next.get(0)] == 0){
			tcur.add(v);
			dfs(p[v].next.get(0));
		}else{
			tcur.add(v);
			int len = tcur.size();
			if(len > ans.size()){
				ans.clear();
				ans.addAll(tcur);
				tcur.clear();
			}
		}
	}
	int type[];

	public void run() {

		InputReader reader = new InputReader(System.in);
		int n = reader.nextInt();
		type = new int[n+1];
		for(int i = 1 ; i <= n ; i ++)
			type[i] = reader.nextInt();
		int a[] = new int[n+1];
		visit = new boolean[n+1];
		Arrays.fill(visit, false);
		p = new point[n+1];
		for(int i = 1 ; i <= n ; i ++){
			p[i] = new point(i);
		}
		for(int i = 1 ; i <= n ; i ++){
			a[i] = reader.nextInt();
			if(a[i] != 0)
				addedge(a[i],i);
		}
		for(int i = 1 ; i <= n ; i ++){
			if(type[i] == 1){
				tcur.clear();
				dfs(i);
			}
		}
		System.out.println(ans.size());
		for(int i = ans.size() - 1 ; i >= 0 ; i --){
			System.out.print(ans.get(i));
			if(i != 0)
				System.out.print(" ");
			else
				System.out.println();
		}

	}

	public static void main(String args[]) {
		new B().run();
	}
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class B {
	private static BufferedReader in;
	private static StringTokenizer st;
	private static PrintWriter out;
	private static boolean[] hotel;

	public static void main(String[] args) throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		st = new StringTokenizer("");
		out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = nextInt();
		hotel = new boolean[n+1];
		for (int i = 1; i <=n; i++) {
			hotel[i] = (nextInt()==1);
		}
		int p[] = new int[n+1];
		int degree[] =  new int[n+1];
		for (int i = 1; i <=n; i++) {
			int v = nextInt();
			if( v != 0){
				p[i] = v;
				degree[v]++;
			}
		}
		int pointer = 0, max = 0;
		for (int i = 1; i <=n; i++) {
			if(hotel[i]){
				int to = p[i];
				int cnt = 0;
				while(degree[to]==1 && !hotel[to]){
					cnt++;
					to = p[to];
				}
				if(max <= cnt){
					max = cnt;
					pointer = i;
				}
			}
		}
		ArrayList<Integer> list = new ArrayList<Integer>();
		out.println(max + 1);
		for (int i = 0; i <=max; i++) {
			list.add(pointer);
			pointer = p[pointer];
		}
		Collections.reverse(list);
		for (Integer i : list) {
			out.print(i+" ");
		}
		out.close();
	}

	static String next() throws IOException{
		while(!st.hasMoreTokens()){
			st = new StringTokenizer(in.readLine());
		}
		return st.nextToken();
	}

	static int nextInt() throws NumberFormatException, IOException{
		return Integer.parseInt(next());
	}

	static long nextLong() throws NumberFormatException, IOException{
		return Long.parseLong(next());
	}

	static double nextDouble() throws NumberFormatException, IOException{
		return Double.parseDouble(next());
	}

}


function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		objects = tokenizeIntegers(readline()),
		parents = tokenizeIntegers(readline()),
		numChildren = new Array(n+1);
	objects.unshift(null);
	parents.unshift(null);
	for (var i = 1; i <= n; ++i) {
		numChildren[i] = 0;
	}
	for (var i = 1; i <= n; ++i) {
		numChildren[parents[i]] += 1;
	}
	var maxLength = 0, maxPath = [];
	for (var i = 1; i <= n; ++i) {
		if (objects[i] == 1) {
			var path = [i], node = i;
			while (true) {
				node = parents[node];
				//print(node, numChildren[node]);
				if (node == 0 || numChildren[node] > 1) {
					break;
				}
				path.push(node);
			}
			if (path.length > maxLength) {
				maxLength = path.length;
				maxPath = path;
			}
		}
	}
	print(maxLength);
	maxPath.reverse();
	print(maxPath.join(' '));
}

main();


def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))

t, = I()
m = [[-1, 0], [0, 1], [1, 0], [0, -1]]
while t:
	t -= 1
	n, = I()
	d1 = [10**5, -10**5]
	d2 = [10**5, -10**5]
	for i in range(n):
		x, y, a1, a2, a3, a4 = I()
		if a1 == 0:
			d1[1] = max(d1[1], x)
		if a2 == 0:
			d2[0] = min(d2[0], y)
		if a3 == 0:
			d1[0] = min(d1[0], x)
		if a4 == 0:
			d2[1] = max(d2[1], y)
	if d1[1] > d1[0]:
		print(0)
		continue
	elif d2[1] > d2[0]:
		print(0)
		continue
	else:
		print(1, d1[0], d2[0])

'''
for i in range(n-1):

'''


def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))

t, = I()
m = [[-1, 0], [0, 1], [1, 0], [0, -1]]
while t:
	t -= 1
	n, = I()
	d1 = [10**20, -10**20]
	d2 = [10**20, -10**20]
	for i in range(n):
		x, y, a1, a2, a3, a4 = I()
		if a1 == 0:
			d1[1] = max(d1[1], x)
		if a2 == 0:
			d2[0] = min(d2[0], y)
		if a3 == 0:
			d1[0] = min(d1[0], x)
		if a4 == 0:
			d2[1] = max(d2[1], y)
	if d1[1] > d1[0]:
		print(0)
		continue
	elif d2[1] > d2[0]:
		print(0)
		break
	else:
		print(1, d1[0], d2[0])

'''
for i in range(n-1):

'''


def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))

t, = I()
m = [[-1, 0], [0, 1], [1, 0], [0, -1]]
while t:
	t -= 1
	n, = I()
	d1 = [10**5, -10**5]
	d2 = [10**5, -10**5]
	for i in range(n):
		x, y, a1, a2, a3, a4 = I()
		if a1 == 0:
			d1[1] = max(d1[1], x)
		if a2 == 0:
			d2[0] = min(d2[0], y)
		if a3 == 0:
			d1[0] = min(d1[0], x)
		if a4 == 0:
			d2[1] = max(d2[1], y)
	if d1[1] > d1[0]:
		print(0)
		continue
	elif d2[1] > d2[0]:
		print(0)
		break
	else:
		print(1, d1[0], d2[0])

'''
for i in range(n-1):

'''


def solve1d(a0, a1):
    if len(a0) == 0:
        if len(a1) == 0:
            return True, 0
        return True, min(a1)
    if len(a1) == 0:
        return True, max(a0)
    m = min(a1)
    M = max(a0)
    if M>m:
        return False, 0
    return True, m

q = int(input())
for i in range(q):
    n = int(input())
    y0 = []
    y1 = []
    x0 = []
    x1 = []
    for j in range(n):
        x, y, f1, f2, f3, f4 = map(int, input().split())
        if f1 == 0:
            x0.append(x)
        if f2 == 0:
            y1.append(y)
        if f3 == 0:
            x1.append(x)
        if f4 == 0:
            y0.append(y)

    tx, x = solve1d(x0, x1)
    ty, y = solve1d(y0, y1)

    if not tx or not ty:
        print(0)
    else:
        print(1, x, y)


def solve1d(a0, a1):
    if len(a0) == 0:
        if len(a1) == 0:
            return True, 0
        return min(a1)
    if len(a1) == 0:
        return True, max(a0)
    m = min(a1)
    M = max(a0)
    if M>m:
        return False, 0
    return True, m

q = int(input())
for i in range(q):
    n = int(input())
    y0 = []
    y1 = []
    x0 = []
    x1 = []
    for j in range(n):
        x, y, f1, f2, f3, f4 = map(int, input().split())
        if f1 == 0:
            x0.append(x)
        if f2 == 0:
            y1.append(y)
        if f3 == 0:
            x1.append(x)
        if f4 == 0:
            y0.append(y)

    tx, x = solve1d(x0, x1)
    ty, y = solve1d(y0, y1)

    if not tx or not ty:
        print(0)
    else:
        print(1, x, y)


q = int(input())
inf  = 10**12
for t in range(q):
    n = int(input())
    l = -inf
    r = inf
    d = -inf
    u = inf
    for m in range(n):
        x, y, *p = [int(e) for e in input().split()]
        if p[0] == 0:
            l = max(l, x)
        if p[1] == 0:
            u = min(u, y)
        if p[2] == 0:
            r = min(r, x)
        if p[3] == 0:
            d = max(d, y)
    if l > r or d > u:
        print(0)
    else:
        print(1, (l + r) // 2, (d + u) // 2)


q = int(input())
inf  = 10**5
for t in range(q):
    n = int(input())
    l = -inf
    r = inf
    d = -inf
    u = inf
    for m in range(n):
        x, y, *p = [int(e) for e in input().split()]
        if p[0] == 0:
            l = max(l, x)
        if p[1] == 0:
            u = min(u, y)
        if p[2] == 0:
            r = min(r, x)
        if p[3] == 0:
            d = max(d, y)
    if l > r or d > u:
        print(0)
    else:
        print(1, (l + r) // 2, (d + u) // 2)


# https://codeforces.com/contest/1196/problem/C
from sys import stdin

MAX = int(1e5)
for _ in range(int(input())):
    n = int(input())
    max_x, max_y = MAX, MAX
    min_x, min_y = -MAX, -MAX
    for _ in range(n):
        x, y, L, U, R, D = map(int, stdin.readline().split())
        if not L:
            min_x = max(min_x, x)
        if not U:
            min_y = max(min_y, y)
        if not R:
            max_x = min(max_x, x)
        if not D:
            max_y = min(max_y, y)

    if min_x <= max_x and min_y <= max_y:
        print(f'1 {min_x} {min_y}')
    else:
        print(0)


# https://codeforces.com/contest/1196/problem/C
from sys import stdin

MAX = int(1e5)
for _ in range(int(input())):
    n = int(input())
    max_x, max_y = MAX, MAX
    min_x, min_y = -MAX, -MAX
    for _ in range(n):
        x, y, L, U, R, D = map(int, stdin.readline().split())
        if not L:
            min_x = max(min_x, x)
        if not U:
            max_y = min(max_y, y)
        if not R:
            max_x = min(max_x, x)
        if not D:
            min_y = max(min_y, y)

    if min_x <= max_x and min_y <= max_y:
        print(f'1 {min_x} {min_y}')
    else:
        print(0)


#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+3;
int n;

int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        int minX = -1e5, maxX = 1e5, minY = -1e5, maxY = 1e5;
        for (int i=0; i<n; i++) {
            int x, y, f1, f2, f3, f4;
            scanf("%d%d%d%d%d%d", &x, &y, &f1, &f2, &f3, &f4);
            if (f1 == 0) minX = max(minX, x);
            if (f3 == 0) maxX = min(maxX, x);
            if (f2 == 0) minY = max(minY, y);
            if (f4 == 0) maxY = min(maxY, y);
        }
        if (minX > maxX || minY > maxY)
            cout << "0\n";
        else
            cout << 1 << ' ' << minX << ' ' << minY << '\n';
    }
}


t = int(input())
for _ in range(t):
    n = int(input())
    minX, maxX = int(-1e5), int(1e5)
    minY, maxY = int(-1e5), int(1e5)
    for i in range(n):
        x, y, f1, f2, f3, f4 = map(int, input().split())
        if (f1 == 0): minX = max(minX, x)
        if (f3 == 0): maxX = min(maxX, x)
        if (f2 == 0): maxY = min(maxY, y)
        if (f4 == 0): minY = max(minY, y)
    if (minX > maxX or minY > maxY):
        print(0)
    else:
        print(1, minX, minY)


maximum = 10 ** 5
q = int(input())
for i in range(q):
    n = int(input())
    x1, y1 = - maximum, -maximum
    x2, y2 = maximum, maximum
    for z in range(n):
        x, y, f1, f2, f3, f4 = [int(j) for j in input().split()]
        if not f1:
            if x > x1:
                x1 = x
        if not f2:
            if y < y2:
                y2 = y
        if not f3:
            if x < x2:
                x2 = x
        if not f4:
            if y > y1:
                y1 = y
    if x2 - x1 < 0 or y2 - y1 < 0:
        print(0)
    else:
        print(1, x1, y1)


maximum = 10 ** 5
q = int(input())
for i in range(q):
    n = int(input())
    x1, y1 = - maximum, -maximum
    x2, y2 = maximum, maximum
    for z in range(n):
        x, y, f1, f2, f3, f4 = [int(j) for j in input().split()]
        if not f1:
            if x > x1:
                x1 = x
        if not f2:
            if y < y2:
                y2 = y
        if not f3:
            if x < x2:
                x2 = x
        if not f4:
            if y > y1:
                y1 = y
        if x2 - x1 < 0 or y2 - y1 < 0:
            print(0)
        else:
            print(1, x1, y1)


def robots(x, y, f1, f2, f3, f4):
    maximum = 10 ** 5
    mnx, mny = - maximum, -maximum
    mxx, mxy = maximum, maximum
    if not f1:
        mnx = max(mnx, x)
    if not f2:
        mxy = min(mxy, y)
    if not f3:
        mxx = min(mxx, x)
    if not f4:
        mny = max(mny, y)
    if mnx <= mxx and mny <= mxy:
        return 1, mnx, mny
    return 0,

q = int(input())
for i in range(q):
    n = int(input())
    X, Y, F1, F2, F3, F4 = [int(j) for j in input().split()]
    print(robots(X, Y, F1, F2, F3, F4))


q = int(input())
for i in range(q):
    n = int(input())
    x, y, f1, f2, f3, f4 = [int(j) for j in input().split()]
    maximum = 10 ** 5
    mnx, mny = - maximum, -maximum
    mxx, mxy = maximum, maximum
    if not f1:
        mnx = max(mnx, x)
    if not f2:
        mxy = min(mxy, y)
    if not f3:
        mxx = min(mxx, x)
    if not f4:
        mny = max(mny, y)
    if mnx <= mxx and mny <= mxy:
        print(1, mnx, mny)
    else:
        print(0)


from collections import Counter,defaultdict,deque
import heapq as hq
import itertools
#from itertools import count, islice
#from functools import reduce
#alph = 'abcdefghijklmnopqrstuvwxyz'
#from math import factorial as fact
#a,b = [int(x) for x in input().split()]
#sarr = [x for x in input().strip().split()]
import math
import sys
input=sys.stdin.readline
def solve():
    n = int(input())
    xmin = -10**5
    xmax = 10**5
    ymin = -10**5
    ymax = 10**5
    for r in range(n):
        arr = [int(x) for x in input().split()]
        f = arr[2:]
        if f[0] == 0:
            xmin = max(xmin,arr[0])
        if f[1] == 0:
            ymax = min(ymax,arr[1])
        if f[2] == 0:
            xmax = min(xmax,arr[0])
        if f[3] == 0:
            ymin = max(ymin,arr[1])
    if ymin<=ymax and xmin<=xmax:
        print(1,xmin,ymin)
    else:
        print(0)

tt = int(input())
for test in range(tt):
    solve()

#


from collections import Counter,defaultdict,deque
import heapq as hq
import itertools
#from itertools import count, islice
#from functools import reduce
#alph = 'abcdefghijklmnopqrstuvwxyz'
#from math import factorial as fact
#a,b = [int(x) for x in input().split()]
#sarr = [x for x in input().strip().split()]
import math
import sys
input=sys.stdin.readline
def solve():
    n = int(input())
    xmin = -10**5
    xmax = 10**5
    ymin = -10**5
    ymax = 10**5
    for r in range(n):
        arr = [int(x) for x in input().split()]
        f = arr[2:]
        if f[0] ==0:
            xmin = arr[0]
        if f[1] ==0:
            ymax = arr[1]
        if f[2] ==0:
            xmax = arr[0]
        if f[3]==0:
            ymin = arr[1]
    if ymin<=ymax and xmin<=xmax:
        print(1,xmin,ymin)
    else:
        print(0)

tt = int(input())
for test in range(tt):
    solve()

#


for _ in range(int(input())):
    U, R = 100000, 100000
    D, L = -100000, 100000
    for _ in range(int(input())):
        x, y, l, u, r, d = map(int,input().split())
        if l==0 and x<L :L=x
        if u==0 and y>U :U=y
        if r==0 and x>R :R=x
        if d==0 and y<D :D=y
if R<L or U<D:print(0)
else: print(1, R, U)


for _ in range(int(input())):
    U, R = 100000, 100000
    D, L = -100000, -100000
    for _ in range(int(input())):
        x, y, l, u, r, d = map(int,input().split())
        if l==0 and x>L :L=x
        if u==0 and y<U :U=y
        if r==0 and x<R :R=x
        if d==0 and y>D :D=y
    if R<L or U<D:print(0)
    else: print(1, R, U)


for _ in range(int(input())):
    U, R = 100000, 100000
    D, L = -100000, 100000
    for _ in range(int(input())):
        x, y, l, u, r, d = map(int,input().split())
        if l==0 and x<L :L=x
        if u==0 and y>U :U=y
        if r==0 and x>R :R=x
        if d==0 and y<D :D=y
    if R<L or U<D:print(0)
    else: print(1, R, U)


T=int(input())
for _ in range(T):
    n=int(input())
    flag=0
    kx1=-100000
    kx2=100000
    ky1=-100000
    ky2=100000
    for i in range(n):
        x,y,f1,f2,f3,f4=map(int,input().split())

        if(f1==0):
            kx1=max(kx1,x)
        if(f2==0):
            ky2=min(ky2,y)
        if(f3==0):
            kx2=min(kx2,x)
        if(f4==0):
            ky1=max(ky1,y)

    if(kx1>kx2 or ky2<ky1):
        print(0)
    else:
        t1=kx1
        t2=ky2
        print(1,t1,t2)


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100000
	x_min = y_min = -100000
	x_fin = set()
	y_fin = set()
	ret = 1
	for r in range(num_rob):
		line = list(map(int, input().split()))
		if not ret:
			continue
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.add(r_x) # if x_fin changed, impossible
			if len(x_fin) > 1:
			    ret = 0
			    continue
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.add(r_y) # if y_fin changed, impossible
			if len(y_fin) > 1:
			    ret = 0
			    continue
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if x_max < x_min:
			ret = 0
			continue
		if y_max < y_min:
			ret = 0
			continue
		for f in x_fin:
			if f > x_max or f < x_min:
				ret = 0
		for f in y_fin:
		    if f > y_max or f < y_min:
		        ret = 0
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin[0]
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin[0]
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100000
	x_min = y_min = -100000
	x_fin = set()
	y_fin = set()
	ret = 1
	for r in range(num_rob):
		line = list(map(int, input().split()))
		if not ret:
			continue
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.add(r_x) # if x_fin changed, impossible
			if len(x_fin) > 1:
			    ret = 0
			    continue
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.add(r_y) # if y_fin changed, impossible
			if len(y_fin) > 1:
			    ret = 0
			    continue
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if x_max < x_min:
			ret = 0
			continue
		if y_max < y_min:
			ret = 0
			continue
		for f in x_fin:
			if f > x_max or f < x_min:
				ret = 0
		for f in y_fin:
		    if f > y_max or f < y_min:
				ret = 0
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin[0]
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin[0]
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100001
	x_min = y_min = -100001
	x_fin = list()
	y_fin = list()
	ret = 1
	for r in range(num_rob):
		if not ret:
			continue
		line = list(map(int, input().split()))
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.append(r_x) # if x_fin changed, impossible
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.append(r_y) # if y_fin changed, impossible
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if len(set(x_fin)) > 1 or len(set(y_fin)) > 1:
			ret = 0
		if x_max < x_min:
			ret = 0
		if y_max < y_min:
			ret = 0
		if x_fin:
			if x_fin[0] > x_max or x_fin[0] < x_min:
				ret = 0
		if y_fin:
			if y_fin[0] > y_max or y_fin[0] < y_min:
				ret = 0
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin[0]
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin[0]
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100000
	x_min = y_min = -100000
	x_fin = set()
	y_fin = set()
	ret = 1
	for r in range(num_rob):
		line = list(map(int, input().split()))
		if not ret:
			continue
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.add(r_x) # if x_fin changed, impossible
			if len(x_fin) > 1:
			    ret = 0
			    continue
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.add(r_y) # if y_fin changed, impossible
			if len(y_fin) > 1:
			    ret = 0
			    continue
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if x_max < x_min:
			ret = 0
			continue
		if y_max < y_min:
			ret = 0
			continue
		for f in x_fin:
			if f > x_max or f < x_min:
				ret = 0
		for f in y_fin:
		    if f > y_max or f < y_min:
		        ret = 0
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin.pop()
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin.pop()
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100000
	x_min = y_min = -100000
	x_fin = list()
	y_fin = list()
	ret = 1
	for r in range(num_rob):
		line = list(map(int, input().split()))
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.append(r_x) # if x_fin changed, impossible
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.append(r_y) # if y_fin changed, impossible
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if len(set(x_fin)) > 1 or len(set(y_fin)) > 1:
			ret = 0
			break
		if x_max < x_min:
			ret = 0
			break
		if y_max < y_min:
			ret = 0
			break
		if x_fin:
			if x_fin[0] > x_max or x_fin[0] < x_min:
				ret = 0
				break
		if y_fin:
			if y_fin[0] > y_max or y_fin[0] < y_min:
				ret = 0
				break
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin[0]
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin[0]
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100001
	x_min = y_min = -100001
	x_fin = list()
	y_fin = list()
	ret = 1
	for r in range(num_rob):
		line = list(map(int, input().split()))
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.append(r_x) # if x_fin changed, impossible
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.append(r_y) # if y_fin changed, impossible
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if len(set(x_fin)) > 1 or len(set(y_fin)) > 1:
			ret = 0
			break
		if x_max < x_min:
			ret = 0
			break
		if y_max < y_min:
			ret = 0
			break
		if x_fin:
			if x_fin[0] > x_max or x_fin[0] < x_min:
				ret = 0
				break
		if y_fin:
			if y_fin[0] > y_max or y_fin[0] < y_min:
				ret = 0
				break
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin[0]
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin[0]
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100000
	x_min = y_min = -100000
	x_fin = list()
	y_fin = list()
	ret = 1
	for r in range(num_rob):
		line = list(map(int, input().split()))
		if not ret:
			continue
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.append(r_x) # if x_fin changed, impossible
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.append(r_y) # if y_fin changed, impossible
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if len(set(x_fin)) > 1 or len(set(y_fin)) > 1:
			ret = 0
		if x_max < x_min:
			ret = 0
		if y_max < y_min:
			ret = 0
		if x_fin:
			if x_fin[0] > x_max or x_fin[0] < x_min:
				ret = 0
		if y_fin:
			if y_fin[0] > y_max or y_fin[0] < y_min:
				ret = 0
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin[0]
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin[0]
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


queries = int(input())
for q in range(queries):
	num_rob = int(input())
	x_max = y_max = 100000
	x_min = y_min = -100000
	x_fin = list()
	y_fin = list()
	ret = 1
	for r in range(num_rob):
		if not ret:
			continue
		line = list(map(int, input().split()))
		r_x, r_y = line[:2]
		lf, up, rt, dn = line[2:]
		if not lf and not rt:
			x_fin.append(r_x) # if x_fin changed, impossible
		elif not lf and rt:
			x_min = max(x_min, r_x)
		elif lf and not rt:
			x_max = min(x_max, r_x)

		if not dn and not up:
			y_fin.append(r_y) # if y_fin changed, impossible
		elif not dn and up:
			y_min = max(y_min, r_y)
		elif dn and not up:
			y_max = min(y_max, r_y)

		if len(set(x_fin)) > 1 or len(set(y_fin)) > 1:
			ret = 0
		if x_max < x_min:
			ret = 0
		if y_max < y_min:
			ret = 0
		if x_fin:
			if x_fin[0] > x_max or x_fin[0] < x_min:
				ret = 0
		if y_fin:
			if y_fin[0] > y_max or y_fin[0] < y_min:
				ret = 0
	res_x, res_y = 0, 0
	if x_fin:
		res_x = x_fin[0]
	else:
		res_x = x_min
	if y_fin:
		res_y = y_fin[0]
	else:
		res_y = y_min
	print(ret, (str(res_x) + " " + str(res_y) if ret else ""))


q=int(input())
while q:
    n=int(input())
    min_x=-10**5
    max_x=+10**5
    min_y=-10**5
    max_y=+10**5
    for i in range(n):
        x,y,f1,f2,f3,f4=map(int,input().split())
        if(f1==0):
            min_x=max(min_x,x)
        if(f2==0):
            max_y=min(max_y,y)
        if(f3==0):
            max_x=min(max_x,x)
        if(f4==0):
            min_y=max(min_y,y)
    if(min_x<=max_x and min_y<=max_y):
        print(1,min_x,min_y)
    else:
        print(0)
    q-=1


INF = 100000

for case in range (int (input ())) :
    n = int (input())

    lim = [-INF, INF, INF, -INF]

    for i in range (n) :
        f = list (map (int, input ().split ()))
        x, y, f = f[0], f[1], f[2:]

        cur = [-INF, INF, INF, -INF]

        for j in range (4) :
            if not f[j] :
                cur[j] = y if (j & 1) else x

        lim = (max (lim[0], cur[0]), min (lim[1], cur[1]), min (lim[2], cur[2]), max (lim[3], cur[3]))

    print (' '.join(map (str, [1, lim[0], lim[1]])) if lim[0] <= lim[2] and lim[1] >= lim[3] else '0')


INF = int (2e9)

for case in range (int (input ())) :
    n = int (input())

    lim = [-INF, INF, INF, -INF]

    for i in range (n) :
        f = list (map (int, input ().split ()))
        x, y, f = f[0], f[1], f[2:]

        cur = [-INF, INF, INF, -INF]

        for j in range (4) :
            if not f[j] :
                cur[j] = y if (j & 1) else x

        lim = (max (lim[0], cur[0]), min (lim[1], cur[1]), min (lim[2], cur[2]), max (lim[3], cur[3]))

    print (' '.join(map (str, [1, lim[0], lim[1]])) if lim[0] <= lim[2] and lim[1] >= lim[3] else '0')


import sys
for q in range(int(input())):
    mxx= 10**5
    mxy = 10 ** 5
    mnx = -10 ** 5
    mny = -10 ** 5

    for n in range(int(input())):
        x,y,f1,f2,f3,f4 = map(int, sys.stdin.readline().split())
        if f1==0: mnx = max(x,mnx)
        if f2==0: mxy = min(y,mxy)
        if f3==0: mxx = min(x,mxx)
        if f4==0: mny = max(y,mny)

    if mnx<=mxx and mny<=mxy:
        print(1,mnx,mny)
    else:
        print(0)


q = int(input())
answer = [[] for i in range(q)]
for question in range(q):
    x = []
    y = []
    f1 = []
    f2 = []
    f3 = []
    f4 = []
    n = int(input())
    for i in range(n):
        xi, yi, f1i, f2i, f3i, f4i = map(int, input().split())
        x.append(xi)
        y.append(yi)
        f1.append(f1i)
        f2.append(f2i)
        f3.append(f3i)
        f4.append(f4i)
    if n == 1:
        answer[question].append(1)
        answer[question].append(x[0])
        answer[question].append(y[0])
        continue
    else:

        sec_41 = []
        sec_21 = []
        sec_23 = []
        sec_34 = []

        for i in range(n):
            if f4[i] == 1 and f1[i] == 1:
                sec_41.append(i)
            if f2[i] == 1 and f1[i] == 1:
                sec_21.append(i)
            if f2[i] == 1 and f3[i] == 1:
                sec_23.append(i)
            if f3[i] == 1 and f4[i] == 1:
                sec_34.append(i)

        if not(sec_41 and sec_21 and sec_23 and sec_34):
            if 1 not in(f1 and f2 and f3 and f4):
                for i in range(n-1):
                    if x[i] != x[i+1]:
                        answer[question].append(0)
                        continue
                    elif y[i] != y[i+1]:
                        answer[question].append(0)
                        continue
                    else:
                        answer[question].append(1)
                        answer[question].append(x[0])
                        answer[question].append(y[0])

        if sec_41:
            minx_41 = 100001
            miny_41 = 100001
            for num in sec_41:
                if x[num] < minx_41:
                    minx_41 = x[num]
                if y[num] < miny_41:
                    miny_41 = y[num]

        if sec_21:
            minx_21 = 100001
            maxy_21 = -100001
            for num in sec_21:
                if x[num] < minx_21:
                    minx_21 = x[num]
                if y[num] > maxy_21:
                    maxy_21 = y[num]

        if sec_23:
            maxx_23 = -100001
            maxy_23 = -100001
            for num in sec_23:
                if x[num] > maxx_23:
                    maxx_23 = x[num]
                if y[num] > maxy_23:
                    maxy_23 = y[num]

        if sec_34:
            maxx_34 = -100001
            miny_34 = 100001
            for num in sec_34:
                if x[num] > maxx_34:
                    maxx_34 = x[num]
                if y[num] < miny_34:
                    miny_34 = y[num]

        if sec_41 and(sec_21 in sec_41) and(sec_23 in sec_41) and (sec_34 in sec_41):
            answer[question].append(1)
            answer[question].append(minx_41)
            answer[question].append(miny_41)
            continue

        if sec_21 and(sec_41 in sec_21) and(sec_23 in sec_21) and(sec_34 in sec_21):
            answer[question].append(1)
            answer[question].append(minx_21)
            answer[question].append(maxy_21)
            continue

        if sec_23 and(sec_41 in sec_23) and(sec_21 in sec_23) and(sec_34 in sec_23):
            answer[question].append(1)
            answer[question].append(maxx_23)
            answer[question].append(maxy_23)
            continue

        if sec_34 and(sec_41 in sec_34) and(sec_21 in sec_34) and(sec_23 in sec_34):
            answer[question].append(1)
            answer[question].append(maxx_34)
            answer[question].append(miny_34)
            continue

        if sec_41:
            if sec_21:
                if maxy_21 - miny_41 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue
            if sec_23:
                if maxx_23 - minx_41 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue
                if maxy_23 - miny_41 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue
            if sec_34:
                if minx_41 - maxx_34 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue

        if sec_21:
            if sec_23:
                if minx_21 - maxx_23 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue
            if sec_34:
                if minx_21 - maxx_34 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue
                if miny_34 - maxy_21 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue

        if sec_23:
            if sec_34:
                if miny_34 - maxy_23 >= 0:
                    pass
                else:
                    answer[question].append(0)
                    continue

        is_exist = []
        exist = ''
        sum_of = 0
        if sec_41:
            is_exist.append(1)
        else:
            is_exist.append(0)
        if sec_21:
            is_exist.append(1)
        else:
            is_exist.append(0)
        if sec_23:
            is_exist.append(1)
        else:
            is_exist.append(0)
        if sec_34:
            is_exist.append(1)
        else:
            is_exist.append(0)

        for j in range(4):
            exist += str(is_exist[j])
            sum_of += is_exist[i]

        if sum_of == 2:
            if exist == '1100':
                answer[question].append(1)
                answer[question].append(min(minx_41, minx_21))
                answer[question].append(miny_41)
            if exist == '1010':
                answer[question].append(1)
                answer[question].append(minx_41)
                answer[question].append(miny_41)
            if exist == '1001':
                answer[question].append(1)
                answer[question].append(minx_41)
                answer[question].append(min(miny_41, miny_34))
            if exist == '0110':
                answer[question].append(1)
                answer[question].append(minx_21)
                answer[question].append(max(maxy_21, maxy_23))
            if exist == '0101':
                answer[question].append(1)
                answer[question].append(minx_21)
                answer[question].append(maxy_21)
            if exist == '0011':
                answer[question].append(1)
                answer[question].append(minx_41)
                answer[question].append(min(miny_34, miny_41))

        if sum_of == 3:
            if exist == '0111':
                answer[question].append(1)
                answer[question].append(max(maxx_34, minx_21))
                answer[question].append(max(maxy_21, miny_34))
            if exist == '1011':
                answer[question].append(1)
                answer[question].append(max(minx_41, maxx_34))
                answer[question].append(min(miny_41, maxy_23))
            if exist == '1101':
                answer[question].append(1)
                answer[question].append(min(minx_21, maxx_34))
                answer[question].append(min(miny_34, maxy_21))
            if exist == '1110':
                answer[question].append(1)
                answer[question].append(min(minx_41, maxx_23))
                answer[question].append(max(miny_41, maxy_23))

        if sum_of == 4:
            answer[question].append(1)
            answer[question].append(max(maxx_34, maxx_23))
            answer[question].append(min(miny_34, miny_41))

for i in range(q):
    print(*answer[i])


q = int(input())
answer = [[] for i in range(q)]
for a in range(q):
    x = []
    y = []
    f1 = []
    f2 = []
    f3 = []
    f4 = []
    n = int(input())
    for i in range(n):
        xi, yi, f1i, f2i, f3i, f4i = map(int, input().split())
        x.append(xi)
        y.append(yi)
        f1.append(f1i)
        f2.append(f2i)
        f3.append(f3i)
        f4.append(f4i)

    maxx = 100000
    maxy = 100000
    minx = -100000
    miny = -100000

    for i in range(n):
        if f1[i] == 0:
            if x[i] > minx:
                minx = x[i]
        if f2[i] == 0:
            if y[i] < maxy:
                maxy = y[i]
        if f3[i] == 0:
            if x[i] < maxx:
                maxx = x[i]
        if f4[i] == 0:
            if y[i] > miny:
                miny = y[i]
    if maxy >= miny:
        if maxx >= minx:
            answer[a].append(1)
            answer[a].append(minx)
            answer[a].append(miny)
        else:
            answer[a].append(0)
            continue
    else:
        answer[a].append(0)
        continue

for i in range(q):
    print(*answer[i])


#import sys
#sys.stdin = open("input11.txt")
T = int(input())
for t in range (T):
    N = int(input())
    x1 = -100000
    x2 = 100000
    y1 = -100000
    y2 = 100000
    for n in range (N):
        x,y,s,a,d,b = map(int,input().split())
        if s == 0:
            x1 = max(x,x1)
        if a == 0:
            y2 = min(y,y2)
        if d == 0:
            x2 = min(x,x2)
        if b == 0:
            y1 = max(y,y1)
    if x1>x2 or y1>y2:
        print(0)
    else:
        q = (x2+x1)//2
        r = (y2+y1)//2
        print(1,q,r)


import sys
sys.stdin = open("input11.txt")
T = int(input())
for t in range (T):
    N = int(input())
    x1 = -100000
    x2 = 100000
    y1 = -100000
    y2 = 100000
    for n in range (N):
        x,y,s,a,d,b = map(int,input().split())
        if s == 0:
            x1 = max(x,x1)
        if a == 0:
            y2 = min(y,y2)
        if d == 0:
            x2 = min(x,x2)
        if b == 0:
            y1 = max(y,y1)
    if x1>x2 or y1>y2:
        print(0)
    else:
        q = (x2+x1)//2
        r = (y2+y1)//2
        print(1,q,r)


def main():
    import sys
    input = sys.stdin.readline

    def solve():
        n = int(input())
        maxx = 10**5
        minx = 0
        maxy = 10**5
        miny = 0

        for _ in range(n):
            x, y, f1, f2, f3, f4 = map(int, input().split())
            if not f1:
                minx = max(minx, x)
            if not f2:
                maxy = min(maxy, y)
            if not f3:
                maxx = min(maxx, x)
            if not f4:
                miny = max(miny, y)

        if minx > maxx or miny > maxy:
            print(0)
        else:
            print(1, minx, miny)

    for _ in range(int(input())):
        solve()

    return 0

main()


def main():
    import sys
    input = sys.stdin.readline

    def solve():
        n = int(input())
        maxx = 10**5
        minx = -10**5
        maxy = 10**5
        miny = -10**5

        for _ in range(n):
            x, y, f1, f2, f3, f4 = map(int, input().split())
            if not f1:
                minx = max(minx, x)
            if not f2:
                maxy = min(maxy, y)
            if not f3:
                maxx = min(maxx, x)
            if not f4:
                miny = max(miny, y)

        if minx > maxx or miny > maxy:
            print(0)
        else:
            print(1, minx, miny)

    for _ in range(int(input())):
        solve()

    return 0

main()


import sys
# sys.stdin = open('inp.txt', 'r')
MAXN = 100005
MAX = 100000
q = 0
n = 0
pos = [[0, 0] for _ in range(MAXN)]
dirs = [[0, 0, 0, 0] for _ in range(MAXN)]
hx = [-1, 0, 1, 0]
hy = [0, 1, 0, -1]
rect = [[0, 0, 0, 0] for _ in range(MAXN)]

def intersect(r1, r2):
    """Find intersection of two rectangles"""
    ret = [0, 0, 0, 0]
    ret[0] = min(r1[0], r2[0])
    ret[1] = max(r1[1], r2[1])
    ret[2] = max(r1[2], r2[2])
    ret[3] = min(r1[3], r2[3])
    if ret[0] < ret[2] or ret[1] > ret[3]:
        return None
    return ret

def solve():
    n = int(input())
    for i in range(n):
        temp = input().split(' ')
        pos[i][0] = int(temp[0])
        pos[i][1] = int(temp[1])
        for j in range(4):
            dirs[i][j] = int(temp[j + 2])
    for i in range(n):
        rect[i][0] = pos[i][0]
        rect[i][1] = pos[i][1]
        rect[i][2] = pos[i][0]
        rect[i][3] = pos[i][1]
        if dirs[i][0] == 1:
            rect[i][2] = -MAX
        if dirs[i][1] == 1:
            rect[i][3] = MAX
        if dirs[i][2] == 1:
            rect[i][0] = MAX
        if dirs[i][3] == 1:
            rect[i][1] = -MAX
    cur_rect = rect[0]
    for i in range(1, n):
        cur_rect = intersect(cur_rect, rect[i])
        if cur_rect == None:
            print(0)
            return
    print(f'1 {cur_rect[0]} {cur_rect[1]}')

if __name__ == '__main__':
    q = int(input())
    for _ in range(q):
        solve()


import sys
#sys.stdin = open("input.txt")

t = int(input())
for i in range (t):
    n = int(input())
    p = []
    for k in range (n):
        x,y,s,a,d,b = map(int,input().split())  #LETTURA
        p.append([x,y,s,a,d,b])
    LD = -100000
    LS = 100000
    LA = 100000
    LB = -100000

    if (n == 1):
        print (1,end=  " ")
        if (LS < LD):
            print (LS,end=" ")
        else:
            print (LD,end=" ")
        if (LA < LB):
            print (LA,end=" ")
        else:
            print (LB,end=" ")
        print()
    else:
        for k in range (n):
            if (p[k][2] == 0):
                if (p[k][0] < LS):
                    LS = p[k][0]
            if (p[k][4] == 0):
                if (p[k][0] > LD):
                    LD = p[k][0]
            if (p[k][3] == 0):
                if (p[k][1] < LA):
                    LA = p[k][1]
            if (p[k][5] == 0):
                if (p[k][1] > LB):
                    LB = p[k][1]
        #print (LD,LS)
        #rint (LA,LB)
        if (LD!=LS and LA != LB):
            print (0)
        else:
            print (1,end=  " ")
            if (LS < LD):
                print (LS,end=" ")
            else:
                print (LD,end=" ")
            if (LA < LB):
                print (LA,end=" ")
            else:
                print (LB,end=" ")
            print()