Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var stations = "";
var subST1 = "";
var subST2 = "";
var ind = 0;

rl.on('line', (input) => {
    if (ind == 0) {
        stations = input;
        ind++;
    } else if (ind == 1) {
        subST1 = input;
        ind++;
    }
    else {
        subST2 = input;
        /** */
        fw = false;
        bw = false;
        fw = ISTrue(stations, subST1, subST2);

        stations = reverceStr(stations);
        bw = ISTrue(stations, subST1, subST2);

        if (fw && bw)
            console.log("both");
        else if (fw)
            console.log("forward");
        else if (bw)
            console.log("backward");
        else
            console.log("fantasy");

        /** */
        rl.close();
    }
});

function ISTrue(s, first, second) {
    let indexOfFirst = s.indexOf(first);
    let lastIndexOFsecond = s.lastIndexOf(second);
    return indexOfFirst != -1 && lastIndexOFsecond != -1 &&
        (indexOfFirst + first.length - 1) < lastIndexOFsecond;
}

function reverceStr(s) {
  /*  let arr = s.split('');
    let limit = parseInt(s.length / 2);
    for (let i = 0, j = s.length - 1; i < limit; i++ , j--) {
        let t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
    return arr.join('');*/
   temp="";
   for(let i=s.length-1;i>=0;i--)
                  temp+=s.charAt(i);

   return  temp;
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var stations = "";
var subST1 = "";
var subST2 = "";
var ind = 0;

rl.on('line', (input) => {
    if (ind == 0) {
        stations = input;
        ind++;
    } else if (ind == 1) {
        subST1 = input;
        ind++;
    }
    else {
        subST2 = input;
        /** */
        fw = false;
        bw = false;
        fw = ISTrue(stations, subST1, subST2);

        stations = reverceStr(stations);
        bw = ISTrue(stations, subST1, subST2);

        if (fw && bw)
            console.log("both");
        else if (fw)
            console.log("forward");
        else if (bw)
            console.log("backward");
        else
            console.log("fantasy");

        /** */
        rl.close();
    }
});

function ISTrue(s, first, second) {
    let indexOfFirst = s.indexOf(first);
    let lastIndexOFsecond = s.lastIndexOf(second);
    return indexOfFirst != -1 && lastIndexOFsecond != -1 &&
        (indexOfFirst + first.length - 1) < lastIndexOFsecond;
}

function reverceStr(s) {
    let arr = s.split('');
    let limit = parseInt(s.length / 2);
    for (let i = 0, j = s.length - 1; i < limit; i++ , j--) {
        let t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
    return arr.join('');
}

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var check = function (flags, first, second) {
  /*for (let i = 0; i < flags.length; i++) {
    if (flags[i]==first) {
      flags.substr(i, first.length);
      for (let j = 0; j < flags.length; j++) {
          if (flags[j]==second)
              return true;
      }
      return false;
    }
  }*/
  let f_f_indx = flags.indexOf(first);
  let l_s_indx = flags.lastIndexOf(second);
  return f_f_indx != -1 && l_s_indx != -1 && f_f_indx + first.length - 1 < l_s_indx;
}

var revFlags = function (str) {
  return str.split("").reverse().join("");
}

var flags, first, second, indicator = 0;

rl.on('line', (input) => {
  if (indicator == 0) {
    flags = input;
    indicator++;
  }
  else if (indicator == 1) {
    first = input;
    indicator++;
  }
  else {
    second = input;

    let f = check(flags, first, second);
    //console.log("flags = %s", flags);
    flags = revFlags(flags);
    //console.log("flags = %s  first = %s second = %s ", flags, first, second);
    let b = check(flags, first, second);

    if (f && b)
      console.log("both");
    else if (f)
      console.log("forward");
    else if (b)
      console.log("backward");
    else
      console.log("fantasy");

    rl.close();
  }

});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
/**
       0123456789|||
flags="abcFFdefgZZhi"
first="FF"
second="ZZ"

A            B
O----------->O   forward

A            B
O<-----------O   backward

A            B
O<----------->O   both

A            B
OX-----------XO   fantasy

       0123456
flags="aaacaaa"
first="aca"
second="aa"

       012345
flags="aaacaa"
first="aca"
second="aa"

 */
//our functions here...
var check = function (flags, first, second) {
    let FInd = flags.indexOf(first);
    let SLInd = flags.lastIndexOf(second);
    return FInd != -1 && SLInd != -1 && FInd + first.length - 1 < SLInd;
}

var revStr = function (s) {
    let ans = "";
    for (let i = s.length - 1; i >= 0; i--)
        ans += s[i];

    return ans;
}

var flags, first, second, indicator = 0;

rl.on('line', (input) => {
    if (indicator == 0) {
        flags = input;
        indicator++;
    }
    else if (indicator == 1) {
        first = input;
        indicator++;
    }
    else {
        second = input;
        //************ */
        //console.log("flags= %s      first= %s      second= %s",flags,first,second);
        let f = check(flags, first, second);
        flags = revStr(flags);
        //console.log("flags= %s      first= %s      second= %s",flags,first,second);
        let b = check(flags, first, second);
        //console.log("flags= %s      first= %s      second= %s   f= %s   b=%s",flags,first,second,f,b);
        if (f && b) console.log("both");
        else if (f) console.log("forward");
        else if (b) console.log("backward");
        else console.log("fantasy");
        /************** */
        rl.close();
    }

});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var check = function (flags, first, second) {
    FIndex = flags.indexOf(first);
    SLIndex = flags.lastIndexOf(second);
    return FIndex != -1 && SLIndex != -1 && FIndex + first.length - 1 < SLIndex;
}

var flags, first, second, identifier = 0

rl.on('line', (input) => {
    if (identifier == 0) {
        flags = input;
        identifier++;
    }
    else if (identifier == 1) {
        first = input;
        identifier++;
    }
    else {
        second = input;
        /*our code here*/
        var f = check(flags,first,second);
        flags = flags.split("").reverse().join("");
        var b = check(flags,first,second);

        if (f && b)
            console.log("both")
        else if (f)
            console.log("forward")
        else if (b)
            console.log("backward")
        else
            console.log("fantasy")

        /**end of our code */
        rl.close();
    }
});

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString='';
let currentLine=0;
process.stdin.on('data',inputStdin=>{
    inputString+=inputStdin;
});
process.stdin.on('end',_=>{
    inputString=inputString.trim().split("\n").map(string=>{
        return string.trim();
    });
    main();
});
function readLine()
{
    return inputString[currentLine++];
}
function rev(s)
{
    return s.split('').reverse().join('');
}
function main()
{
    let s=readLine().trim();
    let a=readLine().trim();
    let b=readLine().trim();
    let x=0;
    let r=rev(s);
    if((s.includes(a))&&(s.includes(b)))
    {
        let aend=s.indexOf(a)+a.length-1,bstart=r.length-r.indexOf(rev(b))-b.length;
        //console.log(aend+' '+bstart);
        if((aend<bstart)&&(aend<s.length)&&(bstart>=0))
        {
           x+=1;
        }
    }
    r=s;
    s=rev(s);
    if((s.includes(a))&&(s.includes(b)))
    {
        let aend=s.indexOf(a)+a.length-1,bstart=r.length-r.indexOf(rev(b))-b.length;
        //console.log(aend+' '+bstart);
        if((aend<bstart)&&(aend<s.length)&&(bstart>=0))
        {
           x+=2;
        }
    }
    if(x===0)
    {
        console.log('fantasy');
    }
    else if(x==1)
    {
        console.log('forward');
    }
    else if(x==2)
    {
        console.log('backward');
    }
    else if(x==3)
    {
        console.log('both');
    }
}

function solve(s, a, b) {
  let forward = false;
  let backward = false;
  const a_indx = s.indexOf(a);
  if (a_indx < 0) {
    // do nothing ...
  } else {
    const b_indx = s.indexOf(b, a_indx + a.length);
    if (b_indx < 0) {
      // do nothing ...
    } else {
      forward = true;
    }
  }
  const s_r = s.split('').reverse().join('');
  const a_indx_r = s_r.indexOf(a);
  if (a_indx_r < 0) {
    // do nothing ...
  } else {
    const b_indx_r = s_r.indexOf(b, a_indx_r + a.length);
    if (b_indx_r < 0) {
      // do nothing ...
    } else {
      backward = true;
    }
  }
  if (forward) {
    if (backward) {
      return 'both';
    } else {
      return 'forward';
    }
  } else {
    if (backward) {
      return 'backward';
    } else {
      return 'fantasy'
    }
  }
};

function main(lines) {
  const trim_lines = [];
  for (const line of lines) {
    const t = line.trim();
    if (t.length > 0) {
      trim_lines.push(t);
    }
  }
  const [s, a, b] = trim_lines;
  const result = solve(s, a, b);
  console.log(result);
};

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding("utf-8");
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
};

processLinesFromStream(process.stdin, main);

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

const input = [];
async function work(line, lineNr) {
    input.push(line);
    if (input.length === 3) {
        const solutionForLine = await solve(input);
        const responseLine = `${solutionForLine}\n`;
        process.stdout.write(responseLine);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(input) {
    const [str, s1, s2] = input;
    let opts = 'init_';
    if (isForward(str, s1, s2)) opts += 'f';
    if (isBackward(str, s1, s2)) opts += 'b';
    const res = {
        'init_': 'fantasy',
        'init_f': 'forward',
        'init_b': 'backward',
        'init_fb': 'both',
    };
    return res[opts];
}

function isForward(str, s1, s2) {
    const s1Index = str.indexOf(s1);
    if (s1Index !== -1) return str.indexOf(s2, s1Index + s1.length) !== -1;
    return false;
}

function isBackward(str, s1, s2) {
    return isForward(str.split('').reverse().join(''), s1, s2);
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var check = function (flags, first, second) {
    let firstIndex = flags.indexOf(first);
    let lastIndex = flags.lastIndexOf(second);
    //console.log("inside check function: \nfirstIndex= %d  lastIndex = %d",firstIndex, lastIndex);
    return firstIndex != -1 && lastIndex != -1 && firstIndex + first.length - 1 < lastIndex;
}

function reverseString(str) {
    return str.split("").reverse().join("");
}
/*

flags= "aaacaaa"
first=" aca"
second= "aa"

*/
/*
C#
while(true){
   string input = Console.ReadLine();

}

nodejs
rl.on('line', (input)=>{

});
*/
var flags, first, second, indicator = 0;
rl.on('line', (input) => {
    if (indicator == 0) {
        flags = input;
        indicator++;
    }
    else if (indicator == 1) {
        first = input;
        indicator++;
    }
    else {
        second = input;
        //our code here.....
        //console.log("flags= %s  first= %s   second= %s",flags, first, second);
        let f = check(flags, first, second);
        flags = reverseString(flags);
        let b = check(flags, first, second);

        if (f && b)
            console.log("both");
        else if (f)
            console.log("forward");
        else if (b)
            console.log("backward");
        else
            console.log("fantasy");

        rl.close();
    }
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var check = function (flags, first, second) {
    fIndx = flags.indexOf(first);
    sIndx = flags.lastIndexOf(second);

    return fIndx != -1 && sIndx != -1 && fIndx + first.length - 1 < sIndx;
}
var flags, first, second, indicator = 0;
rl.on('line', (input) => {
    if (indicator == 0) {
        flags = input;
        indicator++;
    }
    else if (indicator == 1) {
        first = input;
        indicator++;

    }
    else {
        second = input;
        let f = check(flags, first, second);
        flags = flags.split('').reverse().join('');
        let b = check(flags, first, second);

        if (f && b)
            console.log("both");
        else if (f)
            console.log("forward");
        else if (b)
            console.log("backward");
        else
            console.log("fantasy");
        rl.close();
    }
});

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function myFunction(s, array, index) {
  for (var i = index.x; i < array.length; i++) {

    if (s == array.substr(i, s.length))
    {
        index.x = i+s.length;
        return true;
    }
  }
  index.x = 0;
  return false;
}

function reverseString(str) {
  var splitString = str.split("");
  var reverseArray = splitString.reverse();
  var joinArray = reverseArray.join("");
  return joinArray;
}

var n = -1;
var sleep1 = "";
var sleep2 = "";
var array = "";
var index = { x: 0 };
var startToFinish1 = false;
var startToFinish2 = false;
var finishToStart1 = false;
var finishToStart2 = false;
var answer = "";

rl.on("line", input => {
  if (n == -1)
  {
    array = input;
    n=0;
  }
  else if (n == 0) {
    sleep1 = input;
    startToFinish1 = myFunction(sleep1, array, index);
    n++;
  } else {
    sleep2 = input;
    startToFinish2 = myFunction(sleep2, array, index);
    var revarray = reverseString(array);
    index.x = 0;
    finishToStart1 = myFunction(sleep1, revarray, index);
    finishToStart2 = myFunction(sleep2, revarray, index);

    if (startToFinish1 && startToFinish2 && finishToStart1 && finishToStart2)
      answer = "both";
    else if (startToFinish1 && startToFinish2) answer = "forward";
    else if (finishToStart1 && finishToStart2) answer = "backward";
    else answer = "fantasy";
  }
}).on("close", () => {
  console.log(answer);
  //console.log(sleep2);
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var check = function (flags, first, second) {
    var fIndex = flags.indexOf(first);
    var sLastIndex = flags.lastIndexOf(second);

    return fIndex != -1 && sLastIndex != -1 && fIndex + first.length - 1 < sLastIndex;

};

var flags, first, second;
var i = 0;
rl.on('line', (input) => {
    if (i == 0) {
        flags = input;
        i++;
    } else if (i == 1) {
        first = input;
        i++;
    } else {
        second = input;
        /* our code here...
         */
        var f = check(flags, first, second);
        flags = flags.split("").reverse().join("");
        var b = check(flags, first, second);
        if (f && b) console.log("both");
        else if (f) console.log("forward");
        else if (b) console.log("backward");
        else console.log("fantasy");
        rl.close();
        //end of our code....
    }
}).on('close', () => {

});

var fa = readline()
var fs = readline()
var fe = readline()

var f = false
var b = false

var sif = fa.indexOf(fs)
var eif = fa.lastIndexOf(fe)
var sib = fa.lastIndexOf(fs.split('').reverse().join(''))
var eib = fa.indexOf(fe.split('').reverse().join(''))

if (~sif && ~eif && eif - sif >= fs.length) f = true
if (~eib && ~sib && sib - eib >= fe.length) b = true

if (f && b) {print('both')}
else if (f && !b) {print('forward')}
else if (!f && b) {print('backward')}
else {print('fantasy')}

function stringReverse(str) {
  return str.split('').reverse().join('');
}

function check(str, subStr1, subStr2) {
  var index1 = str.indexOf(subStr1), index2 = str.lastIndexOf(subStr2);
  return index1 > -1 && index2 > -1 && index1 + subStr1.length - 1 < index2;
}

function has(first, last) {
  if(first && last) {
    return('both');
  }
  else if(first) {
    return('forward');
  }
  else if(last) {
    return('backward');
  }
  else {
    return('fantasy');
  }
}

var str = readline(), subStr1 = readline(), subStr2 = readline();
print(has(check(str, subStr1, subStr2), check(stringReverse(str), subStr1, subStr2)));

sequence = readline()
firstTest = readline()
secondTest = readline()

isForward = false
isBackward = false

if ((index = sequence.indexOf(firstTest)) >= 0) {
    if (sequence.indexOf(secondTest, index + firstTest.length) >= 0) {
        isForward = true;
    }
}

sequenceReverse = sequence.split("").reverse().join("")

if ((index = sequenceReverse.indexOf(firstTest)) >= 0) {
    if (sequenceReverse.indexOf(secondTest, index + firstTest.length) >= 0) {
        isBackward = true;
    }
}

if (isForward && isBackward) {
    print("both")
} else if (isForward) {
    print("forward")
} else if (isBackward) {
    print("backward")
} else {
    print("fantasy")
}

function reverseString(s)
{
	var str = "";
	for (var i = s.length; i >= 1; i--)
	{
		str += s[i - 1];
	}
	return str;
}

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(reverseString(x));

	var yIndex = s.indexOf(reverseString(y));
	var yLastIndex = s.lastIndexOf(y);

	var forwoardFlag = yLastIndex - xIndex >= x.length;
	if (yLastIndex == -1 || xIndex == -1)
	{
		forwoardFlag = false;
	}

	var backwardFlag = xLastIndex - yIndex >= y.length;
	if (xLastIndex == -1 || yIndex == -1)
	{
		backwardFlag = false;
	}

	if (forwoardFlag && !backwardFlag)
	{
		print("forward");
	}

	else if (!forwoardFlag && backwardFlag)
	{
		print("backward");
	}

	else if (forwoardFlag && backwardFlag)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

var str = readline();
var first = readline();
var second = readline();

function checkStr(str) {
    pos1 = str.indexOf(first);
    flag = false;
    if (pos1 >= 0) {
        str = str.substr(pos1 + first.length);
        pos2 = str.indexOf(second);
        if (pos2 >= 0) flag = true;
    }
    return flag;
}

forwardFlag = checkStr(str);
backwardFlag = checkStr(str.split('').reverse().join(''));

if (forwardFlag && backwardFlag) print('both');
else if (forwardFlag) print('forward');
else if (backwardFlag) print('backward');
else print('fantasy');

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var checkFlags = function(flags, first, second) {
  for (let i = 0; i < flags.length; i++) {
    if (flags[i]==first) {
      flags.substr(i, first.length);
      for (let j = 0; j < flags.length; j++) {
          if (flags[j]==second)
              return true;
      }
      return false;
    }
  }
}

var revFlags = function(str) {
  return str.split("").reverse().join("");
}

var temp = [], forw = false, backw = false;

rl.on('line', (input) => {
    temp.push(input);
    let flags = temp[0], first = temp[1], second = temp[2];
    let reversedFlags = revFlags(flags);

    if (checkFlags(flags,first,second))
      forw = true;
    if (checkFlags(reversedFlags,second,first))
      backw = true;

  }).on('close', function() {

    if (forw && backw)
      console.log("both");
    else if (forw)
      console.log("forward");
    else if (backw)
      console.log("backward");
    else
      console.log("fantasy");

  });

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var check = function (flags, first, second) {

  let f_f_indx = flags.indexOf(first);
  let l_s_indx = flags.lastIndexOf(second);
  return f_f_indx != -1 && l_s_indx != -1 && f_f_indx + first.length - 1 < l_s_indx;
}

var revFlags = function (str) {
  return str.split("").reverse().join("");
}

var flags, first, second, indicator = 0;

rl.on('line', (input) => {
  if (indicator == 0) {
    flags = input;
    indicator++;
  }
  else if (indicator == 1) {
    first = input;
    indicator++;
  }
  else {
    second = input;

    let f = check(flags, first, second);
    let b = check(revFlags(flags), second, first);

    if (f && b)
      console.log("both");
    else if (f)
      console.log("forward");
    else if (b)
      console.log("backward");
    else
      console.log("fantasy");

    rl.close();
  }

});

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString='';
let currentLine=0;
process.stdin.on('data',inputStdin=>{
    inputString+=inputStdin;
});
process.stdin.on('end',_=>{
    inputString=inputString.trim().split("\n").map(string=>{
        return string.trim();
    });
    main();
});
function readLine()
{
    return inputString[currentLine++];
}
function rev(s)
{
    return s.split('').reverse().join('');
}
function main()
{
    let s=readLine().trim();
    let a=readLine().trim();
    let b=readLine().trim();
    let x=0;
    let r=rev(s);
    if((s.includes(a))&&(s.includes(b)))
    {
        let aend=s.indexOf(a)+a.length-1,bstart=r.length-r.indexOf(rev(b))-b.length;
        //console.log(aend+' '+bstart);
        if((aend<bstart)&&(aend<s.length)&&(bstart>=0))
        {
           x+=1;
        }
    }
    r=s;
    s=rev(s);
    if((s.includes(a))&&(s.includes(b)))
    {
        let aend=s.indexOf(a)+a.length-1,bstart=r.length-r.indexOf(rev(b))-b.length;
        //console.log(aend+' '+bstart);
        if((aend<bstart)&&(aend<s.length)&&(bstart>=0))
        {
           x+=2;
        }
    }
    if(x===0)
    {
        console.log('<<fantasy>>');
    }
    else if(x==1)
    {
        console.log('<<forward>>');
    }
    else if(x==2)
    {
        console.log('<<backward>>');
    }
    else if(x==3)
    {
        console.log('<<both>>');
    }
}

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

const input = [];
async function work(line, lineNr) {
    input.push(line);
    if (input.length === 3) {
        const solutionForLine = await solve(input);
        const responseLine = `${solutionForLine}\n`;
        process.stdout.write(responseLine);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(input) {
    const [str, s1, s2] = input;
    let opts = 'init_';
    if (isForward(str, s1, s2)) opts += 'f';
    if (isBackward(str, s1, s2)) opts += 'b';
    const res = {
        'init_': 'fantasy',
        'init_f': 'forward',
        'init_b': 'backward',
        'init_fb': 'both',
    };
    return res[opts];
}

function isForward(str, s1, s2) {
    const s1Index = str.indexOf(s1);
    if (s1Index !== -1) return str.indexOf(s2, s1Index + 1) !== -1;
    return false;
}

function isBackward(str, s1, s2) {
    const s1Index = str.lastIndexOf(s1);
    if (s1Index !== -1) return str.lastIndexOf(s2, s1Index + 1) !== -1;
    return false;
}

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

const input = [];
async function work(line, lineNr) {
    input.push(line);
    if (input.length === 3) {
        const solutionForLine = await solve(input);
        const responseLine = `${solutionForLine}\n`;
        process.stdout.write(responseLine);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(input) {
    const [str, s1, s2] = input;
    let opts = 'init_';
    if (isForward(str, s1, s2)) opts += 'f';
    if (isBackward(str, s1, s2)) opts += 'b';
    const res = {
        'init_': 'fantasy',
        'init_f': 'forward',
        'init_b': 'backward',
        'init_fb': 'both',
    };
    return res[opts];
}

function isForward(str, s1, s2) {
    const s1Index = str.indexOf(s1);
    if (s1Index !== -1) return str.indexOf(s2, s1Index + s1.length) !== -1;
    return false;
}

function isBackward(str, s1, s2) {
    const s1Index = str.lastIndexOf(s1);
    if (s1Index !== -1) return str.lastIndexOf(s2, s1Index + s1.length) !== -1;
    return false;
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var check = function (flags, first, second) {
    let firstIndex = flags.indexOf(first);
    let lastIndex = flags.lastIndexOf(second);
    //console.log("inside check function: \nfirstIndex= %d  lastIndex = %d",firstIndex, lastIndex);
    return firstIndex != -1 && lastIndex != -1 && firstIndex + first.length - 1 < lastIndex;
}

function reverseString(str) {
    return str.split("").reverse().join("");
}
/*

flags= "aaacaaa"
first=" aca"
second= "aa"

*/
/*
C#
while(true){
   string input = Console.ReadLine();

}

nodejs
rl.on('line', (input)=>{

});
*/
var flags, first, second, indicator = 0;
rl.on('line', (input) => {
    if (indicator == 0) {
        flags = input;
        indicator++;
    }
    else if (indicator == 1) {
        first = input;
        indicator++;
    }
    else {
        second = input;
        //our code here.....
        //console.log("flags= %s  first= %s   second= %s",flags, first, second);
        let f = check(flags, first, second);
        flags = reverseString(flags);
        let b = check(flags, first, second);

        if (f && b)
            console.log("both");
        else if (f)
            console.log("forward");
        else if (b)
            console.log("bakward");
        else
            console.log("fantacy");

        rl.close();
    }
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var check = function (flags, first, second) {
    let firstIndex = flags.indexOf(first);
    let lastIndex = flags.lastIndexOf(second);
    //console.log("inside check function: \nfirstIndex= %d  lastIndex = %d",firstIndex, lastIndex);
    return firstIndex != -1 && lastIndex != -1 && firstIndex + first.length - 1 < lastIndex;
}

function reverseString(str) {
    return str.split("").reverse().join("");
}
/*

flags= "aaacaaa"
first=" aca"
second= "aa"

*/
/*
C#
while(true){
   string input = Console.ReadLine();

}

nodejs
rl.on('line', (input)=>{

});
*/
var flags, first, second, indicator = 0;
rl.on('line', (input) => {
    if (indicator == 0) {
        flags = input;
        indicator++;
    }
    else if (indicator == 1) {
        first = input;
        indicator++;
    }
    else {
        second = input;
        //our code here.....
        //console.log("flags= %s  first= %s   second= %s",flags, first, second);
        let f = check(flags, first, second);
        flags = reverseString(flags);
        let b = check(flags, first, second);

        if (f && b)
            console.log("both");
        else if (f)
            console.log("forward");
        else if (b)
            console.log("bakward");
        else
            console.log("fantasy");

        rl.close();
    }
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var check = function (flags, first, second) {
    fIndx = flags.indexOf(first);
    sIndx = flags.lastIndexOf(second);

    return fIndx != -1 && sIndx != -1 && fIndx + first.length - 1 < sIndx;
}
var flags, first, second, indicator = 0;
rl.on('line', (input) => {
    if (indicator == 0) {
        flags = input;
        indicator++;
    }
    else if (indicator == 1) {
        first = input;
        indicator++;

    }
    else {
        second = input;
        let f = check(flags, first, second);
        flags = flags.split('').reverse().join('');
        let b = check(flags, first, second);

        if (f && b)
            console.log("both");
        else if (f)
            console.log("forwards");
        else if (b)
            console.log("backwards");
        else
            console.log("fantasy");
        rl.close();
    }
});

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function myFunction(s, array, index) {
  for (var i = index.x; i < array.length; i++) {
    index.x = i;
    if (s == array.substr(i, s.length)) return true;
  }
  index.x = 0;
  return false;
}

function reverseString(str) {
  var splitString = str.split("");
  var reverseArray = splitString.reverse();
  var joinArray = reverseArray.join("");
  return joinArray;
}

var n = -1;
var sleep1 = "";
var sleep2 = "";
var array = "";
var index = { x: 0 };
var startToFinish1 = false;
var startToFinish2 = false;
var finishToStart1 = false;
var finishToStart2 = false;
var answer = "";

rl.on("line", input => {
  if (n++ == -1) array = input;
  if (n++ == 0) {
    sleep1 = input;
    startToFinish1 = myFunction(sleep1, array, index);
  } else {
    sleep2 = input;
    startToFinish2 = myFunction(sleep2, array, index);
    var revarray = reverseString(array);
    index.x = 0;
    finishToStart1 = myFunction(sleep1, revarray, index);
    finishToStart2 = myFunction(sleep2, revarray, index);

    if (startToFinish1 && startToFinish2 && finishToStart1 && finishToStart2)
      answer = "both";
    else if (startToFinish1 && startToFinish2) answer = "forward";
    else if (finishToStart1 && finishToStart2) answer = "backward";
    else answer = "fantasy";
  }
}).on("close", () => {
  console.log(answer);
});

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function myFunction(s, array, index) {
  for (var i = index.x; i < array.length-s.length; i++) {

    if (s == array.substr(i, s.length))
    {
        index.x = i+s.length;
        return true;
    }
  }
  index.x = 0;
  return false;
}

function reverseString(str) {
  var splitString = str.split("");
  var reverseArray = splitString.reverse();
  var joinArray = reverseArray.join("");
  return joinArray;
}

var n = -1;
var sleep1 = "";
var sleep2 = "";
var array = "";
var index = { x: 0 };
var startToFinish1 = false;
var startToFinish2 = false;
var finishToStart1 = false;
var finishToStart2 = false;
var answer = "";

rl.on("line", input => {
  if (n++ == -1) array = input;
  if (n++ == 0) {
    sleep1 = input;
    startToFinish1 = myFunction(sleep1, array, index);
  } else {
    sleep2 = input;
    startToFinish2 = myFunction(sleep2, array, index);
    var revarray = reverseString(array);
    index.x = 0;
    finishToStart1 = myFunction(sleep1, revarray, index);
    finishToStart2 = myFunction(sleep2, revarray, index);

    if (startToFinish1 && startToFinish2 && finishToStart1 && finishToStart2)
      answer = "both";
    else if (startToFinish1 && startToFinish2) answer = "forward";
    else if (finishToStart1 && finishToStart2) answer = "backward";
    else answer = "fantasy";
  }
}).on("close", () => {
  console.log(answer);
});

function stringReverse(str) {
  return str.split('').reverse().join('');
}

function check(str, subStr1, subStr2) {
  return str.indexOf(subStr1) + subStr1.length - 1 < str.lastIndexOf(subStr2);
}

function has(first, last) {
  if(first && last) {
    return('both');
  }
  else if(first) {
    return('forward');
  }
  else if(last) {
    return('backward');
  }
  else {
    return('fantasy');
  }
}

var str = readline(), subStr1 = readline(), subStr2 = readline();
print(has(check(str, subStr1, subStr2), check(stringReverse(str), subStr1, subStr2)));

function stringReverse(str) {
  return str.split('').reverse().join('');
}

function check(str, subStr1, subStr2) {
  return str.indexOf(subStr1) < str.lastIndexOf(subStr2);
}

function has(first, last) {
  if(first && last) {
    return('both');
  }
  else if(first) {
    return('forward');
  }
  else if(last) {
    return('backward');
  }
  else {
    return('fantasy');
  }
}

var str = readline(), subStr1 = readline(), subStr2 = readline();
print(has(check(str, subStr1, subStr2), check(stringReverse(str), subStr1, subStr2)));

sequence = readline()
firstTest = readline()
secondTest = readline()

isForward = false
isBackward = false

if ((index = sequence.indexOf(firstTest)) >= 0) {
    if (sequence.indexOf(secondTest, index) >= 0) {
        isForward = true;
    }
}

sequenceReverse = sequence.split("").reverse().join("")

if ((index = sequenceReverse.indexOf(firstTest)) >= 0) {
    if (sequenceReverse.indexOf(secondTest, index) >= 0) {
        isBackward = true;
    }
}

if (isForward && isBackward) {
    print("both")
} else if (isForward) {
    print("forward")
} else if (isBackward) {
    print("backward")
} else {
    print("fantasy")
}

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

	if (s[3] == 'a' && s[2] == 'a' && s[0] == 'a')
	{
//		print(s);
		print(x);
		print(y);
	}

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
//		print(xIndex);
//		print(yIndex);
		print("fantasy");
	}

	else if (yLastIndex - xIndex >= x.length && !(xLastIndex - yIndex >= y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex >= x.length) && xLastIndex - yIndex >= y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex >= x.length && xLastIndex - yIndex >= y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
		print("fantasy");
	}

	else if (xIndex < yLastIndex && xLastIndex <= yIndex)
	{
		print("forward");
	}

	else if (xIndex >= yLastIndex && xLastIndex > yIndex)
	{
		print("backward");
	}

	else if (xIndex < yLastIndex && xLastIndex > yIndex)
	{
		print("both");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
		print("fantasy");
	}

	else if (yLastIndex - xIndex > x.length && !(xLastIndex - yIndex > y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex > x.length) && xLastIndex - yIndex > y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex > x.length && xLastIndex - yIndex > y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

	if (s[4] == 'a')
	{
		print(s);
		print(x);
		print(y);
	}

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
//		print(xIndex);
//		print(yIndex);
		print("fantasy");
	}

	else if (yLastIndex - xIndex >= x.length && !(xLastIndex - yIndex >= y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex >= x.length) && xLastIndex - yIndex >= y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex >= x.length && xLastIndex - yIndex >= y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
//		print(xIndex);
//		print(yIndex);
		print("fantasy");
	}

	else if (yLastIndex - xIndex > x.length && !(xLastIndex - yIndex > y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex > x.length) && xLastIndex - yIndex > y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex > x.length && xLastIndex - yIndex > y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
		print("fantasy");
	}

	else if (yLastIndex - xIndex <= x.length && !(xLastIndex - yIndex <= y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex <= x.length) && xLastIndex - yIndex <= y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex <= x.length && xLastIndex - yIndex <= y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

	if (s[3] == 'a' && s[2] == 'a')
	{
		print(s);
		print(x);
		print(y);
	}

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
//		print(xIndex);
//		print(yIndex);
		print("fantasy");
	}

	else if (yLastIndex - xIndex >= x.length && !(xLastIndex - yIndex >= y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex >= x.length) && xLastIndex - yIndex >= y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex >= x.length && xLastIndex - yIndex >= y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

	if (s[3] == 'a')
	{
		print(s);
		print(x);
		print(y);
	}

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
//		print(xIndex);
//		print(yIndex);
		print("fantasy");
	}

	else if (yLastIndex - xIndex >= x.length && !(xLastIndex - yIndex >= y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex >= x.length) && xLastIndex - yIndex >= y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex >= x.length && xLastIndex - yIndex >= y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
		print("fantasy");
	}

	else if (yLastIndex - xIndex >= x.length && !(xLastIndex - yIndex >= y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex >= x.length) && xLastIndex - yIndex >= y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex >= x.length && xLastIndex - yIndex >= y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();

function main()
{
	var s = readline();
	var x = readline();
	var y = readline();

//	print(s);
//	print(x);
//	print(y);

	var xIndex = s.indexOf(x);
	var xLastIndex = s.lastIndexOf(x);
//	print(xIndex + " " + xLastIndex);

	var yIndex = s.indexOf(y);
	var yLastIndex = s.lastIndexOf(y);
//	print(yIndex + " " + yLastIndex);

	if (xIndex == -1 || yIndex == -1)
	{
//		print(xIndex);
//		print(yIndex);
		print("fantasy");
	}

	else if (yLastIndex - xIndex >= x.length && !(xLastIndex - yIndex >= y.length))
	{
		print("forward");
	}

	else if (!(yLastIndex - xIndex >= x.length) && xLastIndex - yIndex >= y.length)
	{
		print("backward");
	}

	else if (yLastIndex - xIndex >= x.length && xLastIndex - yIndex >= y.length)
	{
		print("both");
	}

	else
	{
		print("fantasy");
	}
}

main();


You are given array $$$a_1, a_2, \ldots, a_n$$$, consisting of non-negative integers.Let's define operation of "elimination" with integer parameter $$$k$$$ ($$$1 \leq k \leq n$$$) as follows:  Choose $$$k$$$ distinct array indices $$$1 \leq i_1 < i_2 < \ldots < i_k \le n$$$.  Calculate $$$x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ \ldots ~ \& ~ a_{i_k}$$$, where $$$\&$$$ denotes the bitwise AND operation (notes section contains formal definition).  Subtract $$$x$$$ from each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$; all other elements remain untouched. Find all possible values of $$$k$$$, such that it's possible to make all elements of array $$$a$$$ equal to $$$0$$$ using a finite number of elimination operations with parameter $$$k$$$. It can be proven that exists at least one possible $$$k$$$ for any array $$$a$$$.Note that you firstly choose $$$k$$$ and only after that perform elimination operations with value $$$k$$$ you've chosen initially.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{30}$$$) — array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case, print all values $$$k$$$, such that it's possible to make all elements of $$$a$$$ equal to $$$0$$$ in a finite number of elimination operations with the given parameter $$$k$$$. Print them in increasing order.

NoteIn the first test case:  If $$$k = 1$$$, we can make four elimination operations with sets of indices $$$\{1\}$$$, $$$\{2\}$$$, $$$\{3\}$$$, $$$\{4\}$$$. Since $$$\&$$$ of one element is equal to the element itself, then for each operation $$$x = a_i$$$, so $$$a_i - x = a_i - a_i = 0$$$.  If $$$k = 2$$$, we can make two elimination operations with, for example, sets of indices $$$\{1, 3\}$$$ and $$$\{2, 4\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. For both operations $$$x = 4$$$, so after the first operation $$$a_1 - x = 0$$$ and $$$a_3 - x = 0$$$, and after the second operation — $$$a_2 - x = 0$$$ and $$$a_4 - x = 0$$$.  If $$$k = 3$$$, it's impossible to make all $$$a_i$$$ equal to $$$0$$$. After performing the first operation, we'll get three elements equal to $$$0$$$ and one equal to $$$4$$$. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to $$$0$$$.  If $$$k = 4$$$, we can make one operation with set $$$\{1, 2, 3, 4\}$$$, because $$$x = a_1 ~ \& ~ a_2 ~ \& ~ a_3 ~ \& ~ a_4$$$ $$$= 4$$$. In the second test case, if $$$k = 2$$$ then we can make the following elimination operations:  Operation with indices $$$\{1, 3\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$13 ~ \& ~ 25 = 9$$$. $$$a_1 - x = 13 - 9 = 4$$$ and $$$a_3 - x = 25 - 9 = 16$$$. Array $$$a$$$ will become equal to $$$[4, 7, 16, 19]$$$.  Operation with indices $$$\{3, 4\}$$$: $$$x = a_3 ~ \& ~ a_4$$$ $$$=$$$ $$$16 ~ \& ~ 19 = 16$$$. $$$a_3 - x = 16 - 16 = 0$$$ and $$$a_4 - x = 19 - 16 = 3$$$. Array $$$a$$$ will become equal to $$$[4, 7, 0, 3]$$$.  Operation with indices $$$\{2, 4\}$$$: $$$x = a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$7 ~ \& ~ 3 = 3$$$. $$$a_2 - x = 7 - 3 = 4$$$ and $$$a_4 - x = 3 - 3 = 0$$$. Array $$$a$$$ will become equal to $$$[4, 4, 0, 0]$$$.  Operation with indices $$$\{1, 2\}$$$: $$$x = a_1 ~ \& ~ a_2$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. $$$a_1 - x = 4 - 4 = 0$$$ and $$$a_2 - x = 4 - 4 = 0$$$. Array $$$a$$$ will become equal to $$$[0, 0, 0, 0]$$$. Formal definition of bitwise AND:Let's define bitwise AND ($$$\&$$$) as follows. Suppose we have two non-negative integers $$$x$$$ and $$$y$$$, let's look at their binary representations (possibly, with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of number $$$x$$$, and $$$y_i$$$ is the $$$i$$$-th bit of number $$$y$$$. Let $$$r = x ~ \& ~ y$$$ is a result of operation $$$\&$$$ on number $$$x$$$ and $$$y$$$. Then binary representation of $$$r$$$ will be $$$r_k \dots r_2 r_1 r_0$$$, where:$$$$$$ r_i = \begin{cases} 1, ~ \text{if} ~ x_i = 1 ~ \text{and} ~ y_i = 1 \\ 0, ~ \text{if} ~ x_i = 0 ~ \text{or} ~ y_i = 0 \end{cases} $$$$$$

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const gcd = (a, b) => !b ? a : gcd(b, a%b);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const cnt = Array(30).fill(0);
		for (let i = 0; i < n; i++) {
			for (let j = 0; j < 30; j++) {
				cnt[j] += !!(a[i] & 1 << j);
			}
		}

		let g = 0;
		for (let i = 0; i < 30; i++) {
			g = gcd(g, cnt[i]);
		}

		const ans = [];
		for (let k = 1; k <= n; k++) {
			if (g % k == 0)
				ans.push(k);
		}

		console.log(ans.join(' '));
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const cnt = Array(30).fill(0);
		for (let i = 0; i < n; i++) {
			for (let j = 0; j < 30; j++) {
				cnt[j] += !!(a[i] & 1 << j);
			}
		}

		const ans = [];
		for (let k = 1; k <= n; k++) {
			let ok = true;
			for (let b = 0; ok && b < 30; b++) {
				ok = cnt[b] % k == 0
			}
			if (ok) {
				ans.push(k);
			}
		}

		console.log(ans.join(' '));
	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let res = new Array(31).fill(0);
    for (let i = 0; i < n; i++) {
      let j = arr[i],
        k = 0;
      while (j > 0) {
        if (j & 1) res[k]++;
        j = j >> 1;
        k++;
      }
    }
    let ans = [];
    for (let i = 1; i <= n; i++) {
      let flag = 0;
      for (let j = 0; j < res.length; j++) if (res[j] % i !== 0) flag = 1;
      if (flag === 0) ans.push(i);
    }
    console.log(ans.join(" "));
  }
};
solve();

process.stdin.resume()
process.stdin.setEncoding('utf-8')
let inputBuf = ''
let curLine = 0
process.stdin.on('data', inputData => {
	inputBuf += inputData
})
process.stdin.on('end', _ => {
	inputBuf = inputBuf.trim().split('\n')
	main()
})

const log = (...params) => console.log(...params)
const R = new Proxy({}, {
	get: (target, property, receiver) => {
		if (property === 'i') {
			return parseInt(inputBuf[curLine++], 10)
		} else if (property === 'l') {
			return inputBuf[curLine++]
		} else if (property === 'ii') {
			return inputBuf[curLine++].split(' ').map(s => parseInt(s, 10))
		}
	},
	set: (target, property, value, receiver) => {
		if (property === 'lp') {
			let n = R.i
			for (let i = 0; i < n; i++) value(i)
		}
	}
})
const FLPProxy = new Proxy({}, {
	set: (target, property, value, receiver) => {
		for (let i = 0; i < property; i++) value(i)
	}
})
const F = new Proxy({}, {
	get: (target, property, receiver) => {
		if (property === 'lp') {
			return FLPProxy
		}
	}
})
const A = {
	repeat: (n, value) => Array(n).fill(value),
	range: (l, r) => {
		let arr = Array(r - l)
		for (let i = 0; i < arr.length; i++) arr[i] = i + l
		return arr
	}
}

function main() {
	R.lp=_=>{
		n=R.i
		cnt=R.ii.reduce((p,v)=>{
			F.lp[30]=i=>{
				if(1<<i & v)p[i]++
			}
			return p
		}, A.repeat(30,0))
		ans=A.range(1,n+1).filter(a=>!cnt.some(c=>c%a)).join(' ')
		log(ans)
	}
}


Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it:   At first, choose index $$$i$$$ ($$$1 \leq i \leq n$$$) — starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$).  While $$$i \leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$).  If $$$i > n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible:   Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \overset{+7}{\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$.  Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$.  Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$.  Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$.  Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from $$$1$$$ to $$$n$$$ in such a way as to maximize his result.

NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing $$$i = 1$$$.In the third test case, the maximum score can be achieved by choosing $$$i = 2$$$.In the fourth test case, the maximum score can be achieved by choosing $$$i = 1$$$.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let dp = new Array(n).fill(0);
    for (let i = n - 1; i >= 0; i--) {
      let j = i;
      dp[i] += arr[j];
      if (j + arr[j] < n) {
        dp[i] += arr[j + arr[j]];
        arr[j] = dp[i];
      }
    }
    let max = 0;
    for (let i = 0; i < n; i++) max = Math.max(max, dp[i]);
    console.log(max);
  }
};
solve();

let inputString = '';
let currentLine = 0;
process.stdin.on('data', (data) => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map((str) => str.trim());
	main();
});
function readLine() {
	return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
	for (var a = arguments, r = a[0], i = a.length; --i; )
		r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
	return r;
}
function inv(b) {
	for (var a = MOD, u = 0, v = 1, t; b; v = t)
		(t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
	u %= MOD;
	return u < 0 ? u + MOD : u;
}
function pow(base, n) {
	if (n === 0) return 1;
	let p = pow(base, Math.floor(n / 2));
	let res = mul(mod(p), mod(p));
	if (n % 2 === 1) res = mul(mod(res), base);
	return res;
}
function highestOneBit(i) {
	i |= i >> 1;
	i |= i >> 2;
	i |= i >> 4;
	i |= i >> 8;
	i |= i >> 16;
	return i - (i >>> 1);
}
function permutation(arr, len, store = '', permutations = []) {
	if (store.length === len) {
		permutations.push(store);
		return;
	}
	for (let i = 0; i < arr.length; i++) {
		const newArr = [...arr];
		const newChar = newArr.splice(i, 1);
		permutation(newArr, len, store.concat(newChar), permutations);
	}
	return permutations;
}

function main() {
	let t = +readLine();
	while (t--) {
		const len = +readLine();
		const arr = readLine().split(' ').map(Number);

		for (let i = len - 1; i >= 0; i--) {
			if (i + arr[i] < len) {
				arr[i] += arr[i + arr[i]];
			}
		}
		console.log(`${Math.max(...arr)}`);
	}
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  if (c % 2) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const results = arr.slice();

  for (let i = 0; i < arr.length; i++) {
    let next = i + arr[i];
    if (next < arr.length) {
      results[next] = Math.max(results[i] + arr[next], results[next]);
    }
  }

  console.log(Math.max(...results));

  c++;
});

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  if (c % 2) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const results = arr.slice();
  let ans = 0;

  for (let i = 0; i < arr.length; i++) {
    let next = i + arr[i];
    if (next < arr.length) {
      results[next] = Math.max(results[i] + arr[next], results[next]);
    }
  }

  console.log(Math.max(...results));

  c++;
});

process.stdin.resume();
process.stdin.setEncoding('utf-8');
var stdin_str = '';
var stdin_lines = [];
var cur_line = 0;
function readline() {
    return stdin_lines[cur_line++];
}
process.stdin.on('data', function (raw) {
    stdin_str += raw;
});
process.stdin.on('end', function () {
    stdin_lines = stdin_str.trim().split("\n").map(function (l) { return l.trim(); });
    main();
});
var psi = function (n) { return parseInt(n, 10); };
function f_naive(i, arr) {
    var id = i, score = 0;
    while (id < arr.length) {
        score += arr[id];
        id += arr[id];
    }
    return score;
}
function solve_naive(arr) {
    var max_score = -1;
    for (var i = 0; i < arr.length; i++) {
        max_score = Math.max(max_score, f_naive(i, arr));
    }
    return max_score;
}
function f(i, arr, cache) {
    var id = i;
    if (id + arr[id] < arr.length) {
        cache[id] = arr[id] + cache[id + arr[id]];
    }
    else {
        cache[id] = arr[id];
    }
}
function solve(arr) {
    var cache = Array(arr.length);
    var max_score = -1;
    for (var i = arr.length - 1; i >= 0; i--) {
        f(i, arr, cache);
        max_score = Math.max(max_score, cache[i]);
    }
    return max_score;
}
function main() {
    var nt = psi(readline());
    var _loop_1 = function (_) {
        readline();
        var arr = [];
        readline().split(" ").map(function (n) { return arr.push(psi(n)); });
        console.log(solve(arr));
    };
    for (var _ = 0; _ < nt; _++) {
        _loop_1(_);
    }
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', (data) => {
    inputString += data;
})
process.stdin.on('end', function (){
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => str.trim());
    main();
})
function readLine(){
    return inputString[currentLine++];
}

function main(){
    let t = +readLine();
    while(t--){
        let n = +readLine();
        let a = readLine().split(' ').map(Number);
        let dp = [], ans = 0;
        for(let i=0; i<n; i++){
            dp[i] = 0;
        }
        for(let i=n-1; i>=0; i--){
            dp[i] = a[i];
            let j = i + a[i];
            if(j < n){
                dp[i] += dp[j];
            }
            ans = Math.max(ans, dp[i]);
        }
        console.log(ans);
    }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

function readline() {
  return inputString[currentLine++];
}

function main() {
  const x = readline();

  for (let i = 0; i < x; i++) {
    let n = readline();
    let arr = readline().split(' ').map(x => +x);

    const calculated = {};

    let max = 0;

    for (let i = n; i > 0; i--) {
      let s = i;
      let ans = 0;

      while (s <= n) {
        if (calculated[s]) {
          ans += calculated[s];
          break;
        } else {
          ans += arr[s - 1];
          s += arr[s - 1];
        }
      }
      calculated[i] = ans;
      if (ans > max) {
        max = ans;
      }
    }

    console.log(max);
  }
}

const solve = (n, a) => {
    let map = new Map();
    let max = 0;
    for (let i = n - 1; ~i; i--) {
        let idx = i + 1;
        let sum = 0;
        while (idx <= n) {
            if (map.has(idx)) {
                sum += map.get(idx);
                break;
            }
            sum += a[idx - 1];
            idx += a[idx - 1];
        }
        max = Math.max(max, sum);
        map.set(i + 1, sum);
    }
    console.log(max);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            let data = input.slice(i, i + 2);
            solve(data[0][0], data[1]);
            i += 2;
        }
    });
};

main()

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var n = Number(readline());
        var sum = 0
        var number = 0
        var answer = []
        var xx = 0
        var array = readline().split(' ').map((x, i) => {
            xx = Number(x)
            answer[i + xx] = Math.max(xx + (answer[i] ? answer[i] : 0), answer[i + xx] ? answer[i + xx] : 0)
            answer[i] = (answer[i] ? answer[i] : 0) + xx
            return xx
        });
        var max = 0
        var i = 0
        var x = 0
        while (i < n) {
            x = answer[i]
            if (x > max) max = x
            i++
        }
        console.log(max)
        // console.log(answer)
    })

}

const readline = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout,
});

let nTestCases = 0,
    n,
    t,
    arr = [];

let lineCnt = 0;
readline.on("line", (line) => {
    lineCnt++;

    if (lineCnt === 1) nTestCases = parseInt(line);
    else if (lineCnt % 2 === 0) n = parseInt(line);
    else {
        arr = line.split(" ").map((ele) => parseInt(ele));

        let result = 0;

        const cached = {};

        for (let i = 0; i < n; ++i) {
            let path = i + 1 + arr[i];
            let temp = arr[i];
            while (path <= n) {
                if (cached[path]) {
                    break;
                }
                cached[path] = true;
                temp += arr[path - 1];
                path = path + arr[path - 1];
            }
            if (temp > result) result = temp;
        }
        console.log(result);
    }

    if (lineCnt >= nTestCases * 2 + 1) {
        readline.close();
    }
});

// const n = 3;
// const arr = [2,1,4];
// let result = 0;

// const cached = {};

// for (let i = 0; i < n; ++i) {
//     let path = i + 1 + arr[i];
//     let temp = arr[i];
//     while (path <= n) {
//         if (cached[path]) {
//             break;
//         }
//         cached[path] = true;
//         temp += arr[path - 1];
//         path = path + arr[path - 1];
//     }
//     if (temp > result) result = temp;
// }
// console.log(result);

const write = out => process.stdout.write(out + `\n`);

const mainCode = ([l1, l2]) => {
	l2 = l2.split(' ').map(Number);
	const hashmap = {};
	let highest = 0;

	let i = l2.length - 1;
	while (i >= 0) {
		if (i + l2[i] >= l2.length) hashmap[i] = l2[i];
		else {
			if (l2[i] == 0) hashmap[i] = 0;
			else {
				hashmap[i] = l2[i] + hashmap[i + l2[i]];
			}
		}

		if (hashmap[i] > highest) highest = hashmap[i];
		i--;
	}

	write(highest);
}

let counter = 0;
let t = 0;
const t_size = 2;

const cases = [];

const lineInterpreter = (line) => {
	if (counter == 0) t = Number(line)
	else {
		const cursor = (counter - 1) % t_size
		if (cursor == 0) cases.push([line])
		else cases[cases.length - 1].push(line)
	}

	if (counter == (t * t_size)) {
		cases.map(_case => mainCode(_case))
	}
	counter++
}

const platform = 1;

if (platform > 0) {

	// FOR CODEFORCES

	process.stdin.resume();
	process.stdin.setEncoding('utf-8');

	let inputString = '';
	let currentLine = 0;

	process.stdin.on('data', inputStdin => {
	    inputString += inputStdin;
	});

	process.stdin.on('end', _ => {
	    inputString = inputString.trim().split('\n').map(string => {
	        return string.trim();
	    });

		inputString.map(line => lineInterpreter(line));
	});
} else {

	// FOR PERSONAL USE

	const sample = `4
5
7 3 1 2 3
3
2 1 4
6
2 1000 2 3 995 1
5
1 1 1 1 1`;
	sample.split(`\n`).map(line => lineInterpreter(line));
}

const longJumps = a => {
  let res = 0;
  const n = a.length;
  const dp = Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    dp[i] = dp[i] + a[i];
    res = Math.max(res, dp[i]);
    if (i + a[i] < n) {
      dp[i + a[i]] = Math.max(dp[i + a[i]], dp[i]);
    }
  }
  return res;
};

const main = () => {
  let test = parseInt(readline());
  while (test--) {
    readline();
    const a = readline()
      .split(" ")
      .map(s => parseInt(s));
    console.log(longJumps(a));
  }
};

process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
  inputString += inputStdin;
});

process.stdin.on("end", () => {
  inputString = inputString
    .trim()
    .split("\n")
    .map(string => string.trim());
  main();
});

const readline = () => {
  return inputString[currentLine++];
};

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function getArray(str) {
    return str.split(' ').map(x => Number(x));
}

function getInt(str) {
    return Number(str);
}

function getStrArray(str) {
    return str.split(' ').map(x => x);
}

function create2DArray(rows) {
    var arr = [];

    for (var i = 0; i < rows; i++) {
        arr[i] = [];
    }

    return arr;
}
// ---------------------------------------

function main() {
    let t = getInt(readline());
    while (t--) {
        let len = getInt(readline());
        let arr = getArray(readline());
        let resultArr = new Array(len);
        resultArr.fill(0);
        for(let i = len-1; i>=0; i--) {
            resultArr[i] = arr[i] + (resultArr[i + arr[i]] ? resultArr[i + arr[i]] : 0);
        }
        let max = 0;
        for(let i=0; i< len; i++) {
            max = Math.max(max, resultArr[i]);
        }
        console.log(max);
    }
}

let i = '';
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL).filter((line) => line);
    console.log(processInput(lines));
});

const processInput = (lines) => {
    return lines
        .slice(1)
        .filter((_, i) => i % 2)
        .map((line) => line.split(' ').map((n) => +n))
        .map((nums) => {
            const mapOfScores = new Map();
            for (let i = nums.length - 1; i >= 0; i--) {
                let j = i + nums[i];
                while (j < nums.length) {
                    if (mapOfScores.has(j)) {
                        j += mapOfScores.get(j);
                        break;
                    }
                    j += nums[j];
                }
                mapOfScores.set(i, j - i);
            }
            return Math.max(...mapOfScores.values());
        })
        .join('\n');
};

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray(N);
		var dp = new Array(N).fill(0);
		var max = 0;
		for(var j = N - 1; j >= 0; j--){
			if(j + list[j] >= N){
				dp[j] = Math.max(list[j], dp[j]);
			}else{
				dp[j] += list[j] + dp[j + list[j]];
			}
			max = Math.max(max, dp[j]);
		}
		myout(max);
	}
}

let i = '';
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);

    const t = parseInt(lines[0]);

    for (let i = 1; i <= t * 2; i += 2) {
        const n = parseInt(lines[i]);
        const arr = lines[i + 1].split(' ').map(num => parseInt(num));

        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    const result = [];
    let max = 0;
    let bestIndex = 0;

    for (let i = arr.length - 1; i >= 0; i--) {
        result[i] = arr[i];

        if (i + arr[i] < arr.length) {
            result[i] += result[i + arr[i]];
        }

        if (result[i] > max) {
            max = result[i];
            bestIndex = i;
        }
    }

    return max;
}

"use strict"

let iter = parseInt(readline());

for(let i = 0; i < iter; i++){
    let length = parseInt(readline());
    let arr = readline().split(" ").map(x => parseInt(x));
    let sumMax = 0;

    for(let j = 0; j < length; j++){
        if(arr[j] === 0){
            continue;
        }
        let sumTemp = 0;
        let num;
        for(let k = j; k < length; k += num){
            num = arr[k];
            if(num === 0){
                break;
            }
            sumTemp += num;
            arr[k] = 0;
        }

        if(sumTemp > sumMax){
            sumMax = sumTemp;
        }
    }
    print(sumMax);
}

"use strict"
let t = Number(readline());
while(t--){
	let n = Number(readline());
	let arr = readline().split(' ');
	let resArr = []
	for(let i = n - 1; i >= 0; i--){
		let a = Number(arr[i]);
		resArr[i] = a;
		if(i + a < n) resArr[i] += resArr[i+a];
	}
	print(resArr.reduce((a,b) => a > b ? a : b));
}

var tests = parseInt(readline());
for (var test = 0; test < tests; test++) {
    var size = parseInt(readline());
    var arr = readline().split(' ').map((v) => parseInt(v));
    var mem = [];
    for (var i = arr.length-1; i >= 0; i--) {
        mem[i] = calculate(mem, arr, i);
    }
    print(Math.max(...mem));
}

function calculate(mem, arr, index) {
    var acc = arr[index], nextIndex = index + arr[index];
    if (nextIndex < arr.length) {
        acc += mem[nextIndex];
    }
    mem[index] = acc;
    return mem[index];
}

var tests = parseInt(readline());
for (var test = 0; test < tests; test++) {
    var size = parseInt(readline());
    var arr = readline().split(' ').map((v) => parseInt(v));
    var mem = [];
    for (var i = arr.length-1; i >= 0; i--) {
        mem[i] = calculate(mem, arr, i);
    }
    print(Math.max(...mem));
}

function calculate(mem, arr, index) {
    var acc = 0, i = index;
    while (i < arr.length) {
        if (mem[i] != undefined) {
            acc += mem[i];
            break;
        }
        acc += arr[i];
        i += arr[i];
    }
    mem[index] = acc;
    return mem[index];
}

var limit = parseInt(readline());
var input = new Array();
for (var i = 0; i < limit; i++) {
    input.push(readline());
    input.push(readline());
}
var output = calc(input);
output.forEach(function (value) { print(value); });
function calc(inputArray) {
    var result = new Array();
    for (var i = 0; i < inputArray.length; i += 2) {
        var caseLength = parseInt(inputArray[i]);
        var caseArray = inputArray[i + 1].split(" ");
        var caseIntArray = new Array(inputArray.length);
        var maxTotal = 0;
        for (var j = (caseLength - 1); j >= 0; j--) {
            var currentValue = parseInt(caseArray[j]);
            if ((j + currentValue) < caseLength) {
                currentValue += caseIntArray[j + currentValue];
            }
            caseIntArray[j] = currentValue;
            if (maxTotal < currentValue)
                maxTotal = currentValue;
        }
        result.push(maxTotal);
    }
    return result;
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let dp = new Array(n).fill(0);
    for (let i = n - 1; i >= 0; i--) {
      let j = i;
      dp[i] += arr[j];
      if (j + arr[j] < n) dp[i] += arr[j + arr[j]];
    }
    let max = 0;
    for (let i = 0; i < n; i++) max = Math.max(max, dp[i]);
    console.log(max);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let max = 0;
    for (let i = 0; i < n; i++) max = Math.max(arr[i], max);
    let vis = 0;
    for (let i = 0; i < n; i++) {
      let v = 0,
        j = i;
      while (j < n) {
        v += arr[j];
        j += arr[j];
        vis++;
      }
      max = Math.max(v, max);
      if (vis >= n * 2) break;
    }
    console.log(max);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let max = 0,
      vis = 0;
    for (let i = 0; i < n; i++) {
      let v = 0,
        j = i;
      while (j < n) {
        v += arr[j];
        j += arr[j];
        vis++;
      }
      max = Math.max(v, max);
      if (vis >= n * 2) break;
    }
    console.log(max);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let max = 0,
      vis = 0;
    for (let i = 0; i < n; i++) {
      let v = 0,
        j = i;
      while (j < n) {
        v += arr[j];
        j += arr[j];
        vis++;
      }
      max = Math.max(v, max);
      if (vis === n) break;
    }
    console.log(max);
  }
};
solve();

let inputString = '';
let currentLine = 0;
process.stdin.on('data', (data) => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map((str) => str.trim());
	main();
});
function readLine() {
	return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
	for (var a = arguments, r = a[0], i = a.length; --i; )
		r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
	return r;
}
function inv(b) {
	for (var a = MOD, u = 0, v = 1, t; b; v = t)
		(t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
	u %= MOD;
	return u < 0 ? u + MOD : u;
}
function pow(base, n) {
	if (n === 0) return 1;
	let p = pow(base, Math.floor(n / 2));
	let res = mul(mod(p), mod(p));
	if (n % 2 === 1) res = mul(mod(res), base);
	return res;
}
function highestOneBit(i) {
	i |= i >> 1;
	i |= i >> 2;
	i |= i >> 4;
	i |= i >> 8;
	i |= i >> 16;
	return i - (i >>> 1);
}
function permutation(arr, len, store = '', permutations = []) {
	if (store.length === len) {
		permutations.push(store);
		return;
	}
	for (let i = 0; i < arr.length; i++) {
		const newArr = [...arr];
		const newChar = newArr.splice(i, 1);
		permutation(newArr, len, store.concat(newChar), permutations);
	}
	return permutations;
}

function main() {
	let t = +readLine();
	while (t--) {
		const len = +readLine();
		const _arr = readLine().split(' ').map(Number);
		const arr = [];
		for (let i = 0; i < len; i++) {
			if (_arr[i] === _arr[i + 1]) {
				let [count, j] = [0, i];
				while (_arr[j] === _arr[j + 1]) {
					count += _arr[j];
					j++;
				}
				arr.push(_arr[i] + count);
				i = j;
			} else arr.push(_arr[i]);
		}
		let max = 0;
		for (let i = 1; i <= arr.length; i++) {
			let [c, j] = [0, i];
			while (j <= arr.length) {
				c += arr[j - 1];
				j += arr[j - 1];
			}
			max = Math.max(max, c);
		}
		console.log(max);
	}
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', (data) => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map((str) => str.trim());
	main();
});
function readLine() {
	return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
	for (var a = arguments, r = a[0], i = a.length; --i; )
		r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
	return r;
}
function inv(b) {
	for (var a = MOD, u = 0, v = 1, t; b; v = t)
		(t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
	u %= MOD;
	return u < 0 ? u + MOD : u;
}
function pow(base, n) {
	if (n === 0) return 1;
	let p = pow(base, Math.floor(n / 2));
	let res = mul(mod(p), mod(p));
	if (n % 2 === 1) res = mul(mod(res), base);
	return res;
}
function highestOneBit(i) {
	i |= i >> 1;
	i |= i >> 2;
	i |= i >> 4;
	i |= i >> 8;
	i |= i >> 16;
	return i - (i >>> 1);
}
function permutation(arr, len, store = '', permutations = []) {
	if (store.length === len) {
		permutations.push(store);
		return;
	}
	for (let i = 0; i < arr.length; i++) {
		const newArr = [...arr];
		const newChar = newArr.splice(i, 1);
		permutation(newArr, len, store.concat(newChar), permutations);
	}
	return permutations;
}

function main() {
	let t = +readLine();
	while (t--) {
		const len = +readLine();
		const arr = readLine().split(' ').map(Number);
		let [i, count] = [1, 0];
		while (i <= len) {
			count += arr[i - 1];
			i += arr[i - 1];
		}
		const max = Math.max(...arr);
		const min = Math.min(...arr);

		let cMax = 0;
		let index = arr.findIndex((item) => item === max);
		while (index < len) {
			cMax += arr[index];
			index += arr[index];
		}
		count = Math.max(count, cMax);

		let cMin = 0;
		let minIndex = arr.findIndex((item) => item === min);
		while (minIndex < len) {
			cMax += arr[minIndex];
			minIndex += arr[minIndex];
		}
		count = Math.max(count, cMin);

		if (count < max) console.log(max);
		else console.log(count);
	}
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var n = Number(readline());
        var sum = 0
        var number = 0
        var answer = []
        var xx = 0
        var array = readline().split(' ').map((x, i) => {
            xx = Number(x)
            answer[i + xx] = (answer[i]?answer[i] : 0) + Math.max(xx, answer[i + xx]?answer[i + xx] : 0)
            answer[i] = (answer[i]?answer[i] : 0) + xx
            // console.log((answer[i]?answer[i] : 0) + xx)
            // console.log(answer)

            return xx
        });
        var max = 0
        var i = 0
        var x = 0
        while(i<n){
            x = answer[i]
            if (x > max) max = x
            i++
        }
        console.log(max)
        // console.log(answer)
    })

}

"use strict"

let iter = parseInt(readline());

for(let i = 0; i < iter; i++){
    let length = parseInt(readline());
    let arr = readline().split(" ").map(x => parseInt(x));
    let sumMax = 0;
    let stopFlag = arr[0] > length - 1 ? 1 : arr[0];

    for(let j = 0; j < stopFlag; j++){
        let sumTemp = 0;
        for(let k = j; k < length; k += arr[k]){
            sumTemp += arr[k];
        }

        if(sumTemp > sumMax){
            sumMax = sumTemp;
        }
    }
    print(sumMax);
}