You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA".

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

rl.on('line', (line) => {
  if (line !== null) {
    process.stdout.write(check2(line.toString()) ? 'YES' : 'NO');
  }
})

const check2 = (s) => {
  let ab = -1;
  let ba = -1;

  for (let i = 0; i < s.length; i++) {
    const w = s[i] + s[i + 1];
    if (w === 'AB') {
      if (ab === -1) {
        ab = i;
      }

      if (ba !== -1 && i !== ba + 1 && i !== ba - 1) {
        return true;
      }
    }
    else if (w === 'BA') {
      if (ba === -1) {
        ba = i;
      }

      if (ab !== -1 && i !== ab + 1 && i !== ab - 1) {
        return true;
      }
    }
  }

  return false;
};

const readline = require('readline')

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

RL.on('line', line => {
  const lastIndexOfAB = line.lastIndexOf('AB')
  const lastIndexOfBA = line.lastIndexOf('BA')
  const indexOfAB = line.indexOf('AB')
  const indexOfBA = line.indexOf('BA')
  if (lastIndexOfAB >= 0 && indexOfBA >= 0) {
    if (lastIndexOfAB - indexOfBA >= 2) {
      console.log('YES')
      return
    }
  }
  if (lastIndexOfBA >= 0 && indexOfAB >= 0) {
    if (lastIndexOfBA - indexOfAB >= 2) {
      console.log('YES')
      return
    }
  }
  console.log('NO')
})

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  let s = input[0];
  if (s.length < 4) { console.log('NO'); return; }

  const AB = [];
  const BA = [];

  for (let i = 2; i < s.length; i += 1) {
    if (s[i-2] === 'A' && s[i-1] === 'B') {
      AB.push(i-1);
    }
    else if (s[i-2] === 'B' && s[i-1] === 'A') {
      BA.push(i-1);
    }

    if (s[i-1] === 'A' && s[i] === 'B') {
      AB.push(i);
    }
    else if (s[i-1] === 'B' && s[i] === 'A') {
      BA.push(i);
    }
  }

  AB.forEach(ab => {
    BA.forEach(ba => {
      if (Math.abs(ab - ba) >= 2) {
        console.log('YES'); process.exit(0);
      }
    });
  });

  console.log("NO");
});

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  let s = input[0];

  if (s.length < 4) { console.log('NO'); return; }
  if (s.length === 4) {
    console.log(
     ( (s[0] === 'A' && s[1] === 'B' && s[2] === 'B' && s[3] === 'A') || (s[0] === 'B' && s[1] === 'A' && s[2] === 'A' && s[3] === 'B')) ?
     "YES" : "NO"
    ); return;
  }

  const AB = [];
  const BA = [];
  let find = false;

  //console.log(double[0][0].pos)
  for (let i = 2; i < s.length; i += 1) {
    if (s[i-2] === 'A' && s[i-1] === 'B') {
      AB.push(i-1);
    }
    else if (s[i-2] === 'B' && s[i-1] === 'A') {
      BA.push(i-1);
    }

    if (s[i-1] === 'A' && s[i] === 'B') {
      AB.push(i);
    }
    else if (s[i-1] === 'B' && s[i] === 'A') {
      BA.push(i);
    }
  }

  AB.forEach(ab => {
    BA.forEach(ba => {
      if (Math.abs(ab - ba) >= 2) {
        console.log('YES'); process.exit(0);
      }
    });
  });

  console.log("NO");
});

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

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    let str = input[0];
    if(str.indexOf("AB") !== -1 && str.indexOf("BA") !== -1) {
        if (str.indexOf("AB") < str.lastIndexOf("BA") - 1 || str.indexOf("BA") < str.lastIndexOf("AB") - 1) return console.log('YES');
    }
    console.log('NO');
});

var s = readline();
var n = s.length;

var firstAB = -1, firstBA = -1, lastAB = -1, lastBA = -1;

for(var i=0;i<n-1;i++) {
  if(s[i]=='A' && s[i+1]=='B') {
    if(firstAB==-1) {
      firstAB=i;
    }
    lastAB=i;
  }
  if(s[i]=='B' && s[i+1]=='A') {
    if(firstBA==-1) {
      firstBA=i;
    }
    lastBA=i;
  }
}

if(firstAB==-1 || firstBA==-1) {
  print("NO");
}
else if(lastAB-firstBA>1 || lastBA-firstAB>1) {
  print("YES");
}
else {
  print("NO");
}

function ProblemSolver() {
    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;
    this.CLEAR_ARRAY_PER_CASE = false;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , len ;
        res = 0 ;
        len = this.s.length ;
        this.arr = [] ;
        this.brr = [] ;
        for( i = 0 ; i < len - 1 ; i++ ) {
        	if( this.s.charAt( i ) == 'A'.charAt( 0 ) && this.s.charAt( i + 1 ) == 'B'.charAt( 0 ) ) {
        		this.arr.push( i ) ;
        	}
        	if( this.s.charAt( i ) == 'B'.charAt( 0 ) && this.s.charAt( i + 1 ) == 'A'.charAt( 0 ) ) {
        		this.brr.push( i ) ;
        	}
        }
        for( i = 0 ; i < this.arr.length ; i++ ) {
        	for( j = 0 ; j < this.brr.length ; j++ ) {
        		if( Math.abs( this.arr[ i ] - this.brr[ j ] ) > 1 ) {
        			res = 1 ;
        			break ;
        		}
        	}
        	if( res == 1 ) {
        		break ;
        	}
        }
        if( res == 0 ) {
        	print( 'NO' );
        }
        else {
        	print( 'YES' );
        }
    };

    this.init = function() {
        this.lim1 = 100010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.s = irObj.nextString();
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

    this.clearArraysPerCase = function() {
        var i;
        this.arr = new Array();
        this.adjList = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 );
            this.adjList.push( new Array() );
        }
    };

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    };

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adjList = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( "" );
            this.vis.push( 0 );
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.adjList.push( new Array() );
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() );
            this.done.push( new Array() );
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 );
                this.done[ i ].push( 0 );
            }
        }
    };

    this.init();
}

function InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine;
        while( true ) {
            try {
                singleLine = readline();
                if( singleLine == null ) {
                    break;
                }
            }
            catch( ex ) {
                break;
            }
            this.allLines.push( singleLine );
        }
    };

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    };

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    };

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    };

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString );
                currentString = "";
            }
            else {
                currentString += data[ i ];
            }
        }
        if( currentString != "" ) {
            this.allLines.push( currentString );
        }
    };

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            res = "";
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++;
            this.currrentCharacterIndex = 0;
            return res;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( "No more tokens available!" );
            }
            startIdx = -1;
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i;
                    break;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
                continue;
            }
            res = "";
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );
                }
            }
            this.currrentCharacterIndex = endIdx;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            return res;
        }
    };

    this.nextInt = function() {
        return parseInt( this.next( 1 ) );
    };

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) );
    };

    this.nextString = function() {
        return this.next( 1 );
    };

    this.nextLine = function() {
        return this.next( 0 );
    };
}

function FileOutputHandler() {
    this.resultantStringArray = new Array();

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString );
    };

    this.clearPercase = function() {
        this.resultantStringArray = new Array();
    };

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

function CodeExecutioner() {
    this.irObj = new InputReader();
    this.psObj = new ProblemSolver();
    this.fohObj = new FileOutputHandler();

    this.runCases = function() {
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt();
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase();
                this.psObj.getInput( this.irObj );
                this.psObj.solveCase();
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase();
                hasMoreTestCases = this.psObj.getInput( this.irObj );
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase();
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );
        }
    };

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {
                    environmentType = 'local-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    };

    this.configureStreamsAndReadInput = function() {
        var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments );
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino();
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
    };

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

function toi(x){return parseInt(x);}
(function(){
    function isp(s,ts){
	var index=0;
	var state=0;
	while(index!=s.length){
	    switch(state){
	    case 0:
		if(s[index]==ts[state]){
		    state=1;
		}else{
		    state=0;
		}
		break;
	    case 1:
		if(s[index]==ts[state]){
		    state=2;
		}else if(s[index]==ts[state-1]){
		    state=1;
		}else{
		    state=0;
		}
		break;
	    case 2:
		if(s[index]==ts[state]){
		    state=3;
		}else{
		    state=2;
		}
		break;
	    case 3:
		if(s[index]==ts[state]){
		    state=4;
		}else if(s[index]==ts[state-1]){
		    state=3;
		}else{
		    state=2;
		}
		break;
	    }
	    index++;
	    if(state==4)return true;
	}
	return false;
    }
    var s=readline();
    if(isp(s,"ABBA")||isp(s,"BAAB")){
	print("YES");
    }else{
	print("NO");
    }
})();

var n = readline();
var len = n.length;
s1 = n;
s2 = n;
s1 = s1.replace("AB", ".");
s1 = s1.replace("BA", ".");
s1 = s1.replace(".", "");
s1 = s1.replace(".", "");
s2 = s2.replace("BA", ".");
s2 = s2.replace("AB", ".");
s2 = s2.replace(".", "");
s2 = s2.replace(".", "");
if(s1.length <= len - 4 || s2.length <= len - 4){
    print("YES");
}
else{
    print("NO");
}

var str = readline();
var reg1 = /BA.*?AB/;
var reg2 = /AB.*?BA/;
//str = str.replace(/BA/gi, "");
reg1.test(str)||reg2.test(str)?print("YES"):print("NO");

var str = readline();
var r1 = /AB/g;
var r2 = /BA/g;
var result1 = [],result2 = [];
var match;

while (match = r1.exec(str))
   result1.push(match.index);

while (match = r2.exec(str))
   result2.push(match.index);

var flag = 0;
for(var i = 0; i < result1.length; i++)
	for(var j = 0; j < result2.length; j++)
		if(Math.abs(result1[i]- result2[j]) >= 2){
			flag = 1;
			break;
		}

print((flag)?"YES":"NO");

function main() {
    var line = readline();
    var baFound = 0;
    var abFound = 0;
    var abaFound = 0;
    for(var i=0;i<line.length-1;i++){
        var s = line[i] + line[i+1] + (line[i+2] || "X");
        var s2 = line[i] + line[i+1];
        if(s == "ABA" || s == "BAB"){
            abaFound++;
            i+=2;
            continue;
        }
        if(s2 == "AB"){
            abFound++;
            i++;
        }
        if(s2 == "BA"){
            baFound++;
            i++;
        }
    }
    if(abaFound >= 2 || (abaFound >= 1 && (abFound >=1 || baFound >=1) ) || (abFound  >= 1 && baFound >=1)){
        print("YES")
    } else {
        print("NO")
    }
}

main()

(function main(){
    http://codeforces.com/problemset/problem/550/A

    var linea = readline();

    if(/AB.*?BA/.test(linea) || /BA.*?AB/.test(linea)){
        write("YES");
    }else{
        write("NO");
    }
})();

var input = readline().split('');

var findAB = Infinity;
var findBA = Infinity;
var ABFlag = false;
var BAFlag = false;
for (var i = 0; i < input.length - 1; i++) {
    if (input[i] == 'A' && input[i+1] == 'B') {
        findAB = Math.min(findAB, i);
        if (findBA == Infinity) ABFlag = true;
        else if (Math.abs(i - findBA) > 1) { ABFlag = true; BAFlag = true; }
    }
    if (input[i] == 'B' && input[i+1] == 'A') {
        findBA = Math.min(findBA, i);
        if (findAB == Infinity) BAFlag = true;
        else if (Math.abs(i - findAB) > 1) { ABFlag = true; BAFlag = true; }
    }
}
write((BAFlag && ABFlag) ? 'YES' : 'NO')

const check = (s) => {
  let ab = -1;
  let ba = -1;

  for (let i = 0; i < s.length; i++) {
    const w = s[i] + s[i + 1];
    if (w === 'AB') {
      if (ab === -1) {
        ab = i;
      }

      if (ba !== -1 && i !== ba + 1 && i !== ba - 1) {
        return true;
      }
    }
    else if (w === 'BA') {
      if (ba === -1) {
        ba = i;
      }

      if (ab !== -1 && i !== ab + 1 && i !== ab - 1) {
        return true;
      }
    }
  }

  return false;
};

process.stdin.on('readable', () => {
  const chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write(check(chunk.toString()) ? 'YES' : 'NO');
    process.stdout.write("\n");
  }
});

const check = (s) => {
  let ab = -1;
  let ba = -1;

  const n = s.length;
  let i = 0;
  let j = n - 1;
  while (i <= n / 2 && j >= n / 2) {
    const wi = s[i] + s[i + 1];

    if (wi === 'AB') {
      if (ab === -1) {
        ab = i;
      } else if (ba !== -1 && i !== ba + 1 || i !== ba - 1) {
        return true;
      }
    }
    else if (wi === 'BA') {
      if (ba === -1) {
        ba = i;
      } else if (ab !== -1 && i !== ab + 1 || i !== ab - 1) {
        return true;
      }
    }

    const wj = s[j - 1] + s[j];

    if (wj === 'AB') {
      if (ab === -1) {
        ab = j;
      } else if (ba !== -1 && j !== ba + 1 || j !== ba - 1) {
        return true;
      }
    }
    else if (wj === 'BA') {
      if (ba === -1) {
        ba = j;
      } else if (ab !== -1 && j !== ab + 1 || j !== ab - 1) {
        return true;
      }
    }

    i++;
    j--;
  }

  return false;
}

process.stdin.on('readable', () => {
  const chunk = process.stdin.read();
  if (chunk !== null) {
    process.stdout.write(check(chunk.toString()) ? 'YES' : 'NO');
    process.stdout.write("\n");
  }
});

const readline = require('readline')

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

RL.on('line', line => {
  let rLine = line.replace('AB', '')
  if (rLine === line) {
    console.log('NO')
  } else if (rLine.replace('BA', '') === rLine) {
    console.log('NO')
  } else {
    console.log('YES')
  }
})

const readline = require('readline')

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

RL.on('line', line => {
  const lastIndexOfAB = line.lastIndexOf('AB')
  const lastIndexOfBA = line.lastIndexOf('BA')
  const indexOfAB = line.indexOf('AB')
  const indexOfBA = line.indexOf('BA')
  if (lastIndexOfAB > 0 && indexOfBA > 0) {
    if (lastIndexOfAB - indexOfBA >= 2) {
      console.log('YES')
    }
  }
  if (lastIndexOfBA > 0 && indexOfAB > 0) {
    if (lastIndexOfBA - indexOfAB >= 2) {
      console.log('YES')
    }
  }
  console.log('NO')
})

const readline = require('readline')

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

RL.on('line', line => {
  const lastIndexOfAB = line.lastIndexOf('AB')
  const lastIndexOfBA = line.lastIndexOf('BA')
  const indexOfAB = line.indexOf('AB')
  const indexOfBA = line.indexOf('BA')
  if (lastIndexOfAB - indexOfBA >= 2 || lastIndexOfBA - indexOfAB >= 2) {
    console.log('YES')
  } else {
    console.log('NO')
  }
})

const readline = require('readline')

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

RL.on('line', line => {
  let rABLine = line.replace('AB', '')
  let rBALine = line.replace('BA', '')
  if (rABLine === line && rBALine === line) {
    console.log('NO')
  } else if (rABLine.replace('BA', '') === rABLine && rBALine.replace('AB') === rBALine ) {
    console.log('NO')
  } else {
    console.log('YES')
  }
})

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  let s = input[0];

  if (s.length < 4) { console.log('NO'); return; }

  const double = [ [0, 0], [0, 0] ];
  let find = false;

  //console.log(double[0][0].pos)
  for (let i = 2; i < s.length; i += 1) {
    if (s[i-2] === 'A' && s[i-1] === 'B') {
      if (double[1][1] === 1) { console.log('YES'); return; }
      double[0][0] = 1; find = true;
    }
    else if (s[i-2] === 'B' && s[i-1] === 'A') {
      if (double[1][0] === 1) { console.log('YES'); return; }
       double[0][1] = 1; find = true;
     }

    if (s[i-1] === 'A' && s[i] === 'B') {
      if (!find && double[0][1] === 1) { console.log('YES'); return; }
      double[1][0] = 1; find = true;
    }
    else if (s[i-1] === 'B' && s[i] === 'A') {
      if (!find && double[0][0] === 1) { console.log('YES'); return; }
      double[1][1] = 1; find = true;
    }

    if (find) { i += 1; find = false; }
  }

  console.log(
    ((double[0][0] === 1 && double[0][1]) || (double[1][0] === 1 && double[1][1] === 1)) ? "YES" : "NO"
  );
});

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  let s = input[0];
  let answer = false;

  if (s.length < 4) { console.log('NO'); return; }

  const double = [[0, 0], [0, 0]];

  for (let i = 2; i < s.length; i += 1) {
    if (s[i-2] === 'A' && s[i-1] === 'B') double[0][0] = 1;
    else if (s[i-2] === 'B' && s[i-1] === 'A') double[0][1] = 1;

    if (s[i-1] === 'A' && s[i] === 'B') double[0][0] = 1;
    else if (s[i-1] === 'B' && s[i] === 'A') double[0][1] = 1;
  }

  console.log(
    ((double[0][0] === 1 && double[0][1]) || (double[1][0] === 1 && double[1][1] === 1)) ? "YES" : "NO"
  );
});

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  let s = input[0];

  if (s.length < 4) { console.log('NO'); return; }

  const double = [ [0, 0], [0, 0] ];
  let find = false;

  //console.log(double[0][0].pos)
  for (let i = 2; i < s.length; i += 1) {
    if (s[i-2] === 'A' && s[i-1] === 'B') {
      if (double[1][1] === 1) { console.log('YES'); return; }
      double[0][0] = 1; find = true;
    }
    else if (s[i-2] === 'B' && s[i-1] === 'A') {
      if (double[1][0] === 1) { console.log('YES'); return; }
       double[0][1] = 1; find = true;
     }

    if (s[i-1] === 'A' && s[i] === 'B') {
      if (!find && double[0][1] === 1) { console.log('YES'); return; }
      double[1][0] = 1; find = true;
    }
    else if (s[i-1] === 'B' && s[i] === 'A') {
      if (!find && double[0][0] === 1) { console.log('YES'); return; }
      double[1][1] = 1; find = true;
    }

    if (find) { if (s.length >= 5) i += 1; find = false; }
  }

  console.log(
    ((double[0][0] === 1 && double[0][1]) || (double[1][0] === 1 && double[1][1] === 1)) ? "YES" : "NO"
  );
});

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  let s = input[0];

  if (s.length < 4) { console.log('NO'); return; }

  const double = [ [0, 0], [0, 0] ];
  let find = false;

  //console.log(double[0][0].pos)
  for (let i = 2; i < s.length; i += 1) {
    if (s[i-2] === 'A' && s[i-1] === 'B') { double[0][0] = 1; find = true; }
    else if (s[i-2] === 'B' && s[i-1] === 'A') { double[0][1] = 1; find = true; }

    if (s[i-1] === 'A' && s[i] === 'B') {
      if (!find && double[0][1] === 1) { console.log('YES'); return; }
      double[1][0] = 1; find = true;
    }
    else if (s[i-1] === 'B' && s[i] === 'A') {
      if (!find && double[0][0] === 1) { console.log('YES'); return; }
      double[1][1] = 1; find = true;
    }

    if (find) { i += 1; find = false; }
  }

  console.log(
    ((double[0][0] === 1 && double[0][1]) || (double[1][0] === 1 && double[1][1] === 1)) ? "YES" : "NO"
  );
});

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  let s = input[0];

  if (s.length < 4) { console.log('NO'); return; }
  if (s.length === 4) {
    console.log(
     ( (s[0] === 'A' && s[1] === 'B' && s[2] === 'B' && s[3] === 'A') || (s[0] === 'B' && s[1] === 'A' && s[2] === 'A' && s[3] === 'B')) ?
     "YES" : "NO"
    ); return;
  }

  const double = [ [0, 0], [0, 0] ];
  let find = false;

  //console.log(double[0][0].pos)
  for (let i = 2; i < s.length; i += 1) {
    if (s[i-2] === 'A' && s[i-1] === 'B') {
      if (double[1][1] === 1 && s.length >= 5) { console.log('YES'); return; }
      double[0][0] = 1; find = true;
    }
    else if (s[i-2] === 'B' && s[i-1] === 'A') {
      if (double[1][0] === 1  && s.length >= 5) { console.log('YES'); return; }
       double[0][1] = 1; find = true;
     }

    if (s[i-1] === 'A' && s[i] === 'B') {
      if (!find && double[0][1] === 1) { console.log('YES'); return; }
      double[1][0] = 1; find = true;
    }
    else if (s[i-1] === 'B' && s[i] === 'A') {
      if (!find && double[0][0] === 1) { console.log('YES'); return; }
      double[1][1] = 1; find = true;
    }

    if (find) { if (s.length >= 5) i += 1; find = false; }
  }

  console.log(
    ((double[0][0] === 1 && double[0][1]) || (double[1][0] === 1 && double[1][1] === 1)) ? "YES" : "NO"
  );
});

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

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    let str = input[0];
    if (str.indexOf("AB") < str.lastIndexOf("BA") - 1) console.log('YES');
    else console.log('NO');
});

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

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    const str = input[0];
    if (str.split("AB").includes("BA")) console.log("YES");
    else console.log("NO");
});

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

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    const str = input[0];
    if (str.split("AB").join("").includes("BA")) console.log("YES");
    else console.log("NO");
});

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

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    let str = input[0];
    if(str.indexOf("AB") !== -1 && str.indexOf("BA") !== -1) {
        if (str.indexOf("AB") < str.lastIndexOf("BA") - 1 || str.indexOf("BA") < str.lastIndexOf("AB") - 1) console.log('YES');
    }
    console.log('NO');
});

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

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    let str = input[0];
    if (str.indexOf("AB") < str.lastIndexOf("BA") - 1 || str.indexOf("BA") < str.lastIndexOf("AB") - 1) console.log('YES');
    else console.log('NO');
});

var n = readline();
var len = n.length;
s1 = n;
s2 = n;
s1 = s1.replace("AB", "");
s1 = s1.replace("BA", "");
s2 = s2.replace("AB", "");
s2 = s2.replace("BA", "");
if(s1.length <= len - 4 || s2.length <= len - 4){
    print("YES");
}
else{
    print("NO");
}

var n = readline();
var len = n.length;
n = n.replace("AB", "");
n = n.replace("BA", "");
if(n.length <= len - 4){
    print("YES");
}
else{
    print("NO");
}

var n = readline();
var len = n.length;
s1 = n;
s2 = n;
s1 = s1.replace("AB", "");
s1 = s1.replace("BA", "");
s2 = s2.replace("BA", "");
s2 = s2.replace("AB", "");
if(s1.length <= len - 4 || s2.length <= len - 4){
    print("YES");
}
else{
    print("NO");
}

var str = readline();
var reg = /AB/;
str = str.replace(/BA/gi, "");
reg.test(str)==true? print("YES"):print("NO");

var str = readline();
var reg = /(BA.*AB)||(AB.*BA)/;
//str = str.replace(/BA/gi, "");
reg.test(str)==true? print("YES"):print("NO");

var str = readline();
var r1 = /AB/g;
var r2 = /BA/g;
var result1 = [],result2 = [];
var match;

while (match = r1.exec(str))
   result1.push(match.index);

while (match = r2.exec(str))
   result2.push(match.index);

var flag = 0;
for(var i = 0; i < result1.length; i++)
	for(var j = 0; j < result2.length; j++)
		if(result1[i]- result2[j] >= 2){
			flag = 1;
			break;
		}

print((flag)?"YES":"NO");

var res = readline().match(/ABABA|BABAB|AB|BA/g);
var s = [0,0];
flag = 0;
if(res){
	for(var i = 0; i < res.length; i++){
		if(res[i] == "AB")
			s[0] = 1;
		else if(res[i] == "BA")
			s[1] = 1;
		else if(res[i] == "ABABA" || res[i] == "BABAB"){
			flag = 1;
			break;
		}
		if(s[0] == 1 && s[1] == 1){
			flag = 1;
			break;
		}
	}
	print((flag==1) ? "YES" : "NO");
}
else
	print("NO");

var res = readline().match(/AB|BA/g);
var s = [0,0];
flag = 0;
if(res){
	for(var i = 0; i < res.length; i++){
		if(res[i] == "AB")
			s[0] = 1;
		else if(res[i] == "BA")
			s[1] = 1;
		if(s[0] == 1 && s[1] == 1){
			flag = 1;
			break;
		}
	}
	print((flag==1) ? "YES" : "NO");
}
else
	print("NO");

var str = readline();
var r1 = /AB/g;
var r2 = /BA/g;
var result1 = [],result2 = [];
var match;

while (match = r1.exec(str))
   result1.push(match.index);

while (match = r2.exec(str))
   result2.push(match.index);

print(result1);
print(result2);

var flag = 0;
for(var i = 0; i < result1.length; i++)
	for(var j = 0; j < result2.length; j++)
		if(Math.abs(result1[i]- result2[j]) >= 2){
			flag = 1;
			break;
		}

print((flag)?"YES":"NO");

function main() {
    var line = readline();
    var baFound = 0;
    var abFound = 0;
    var abaFound = 0;
    for(var i=0;i<line.length-1;i++){
        var s = line[i] + line[i+1] + (line[i+2] || "X");
        var s2 = line[i] + line[i+1];
        if(s == "ABA" || s == "BAB"){
            abaFound++;
            i+=2;
            continue;
        }
        if(s2 == "AB"){
            abFound++;
            i++;
        }
        if(s2 == "BA"){
            baFound++;
            i++;
        }
    }
    if(abaFound >= 2 || abFound + baFound >= 2){
        print("YES")
    } else {
        print("NO")
    }
}

main()

function main() {
    var line = readline();
    var baFound = 0;
    var abFound = 0;
    var abaFound = 0;
    for(var i=0;i<line.length-1;i++){
        var s = line[i] + line[i+1] + (line[i+2] || "X");
        var s2 = line[i] + line[i+1];
        if(s == "ABA" || s == "BAB"){
            abaFound++;
            i+=2;
            continue;
        }
        if(s2 == "AB"){
            abFound++;
            i++;
        }
        if(s2 == "BA"){
            baFound++;
            i++;
        }
    }
    if(abaFound >= 2 || (abFound  >= 1 && baFound >=1)){
        print("YES")
    } else {
        print("NO")
    }
}

main()

(function main(){
    http://codeforces.com/problemset/problem/550/A

    var linea = readline();

    var regex = /(AB|BA)/g;

    var numeroMatches = 0;

    while(regex.test(linea) && numeroMatches <4){
        numeroMatches++;
    }
    if(numeroMatches == 2){
        write("YES");
    }else{
        write("NO");
    }
})();

(function main(){
    http://codeforces.com/problemset/problem/550/A

    var linea = readline();

    var regex = /(AB|BA)/g;

    var numeroMatches = 0;

    while(regex.test(linea) || numeroMatches <2){
        numeroMatches++;
    }
    if(numeroMatches == 2){
        write("YES");
    }else{
        write("NO");
    }
})();

(function main(){
    http://codeforces.com/problemset/problem/550/A

    var linea = readline();

    var regex = /(AB|BA)/g;
    var matches = linea.match(regex);
    if(matches === null){
        write("NO");
        return;
    }

    var matches = matches.toString();
    if(matches.includes("AB") && matches.includes("BA")){
        write("YES");
    }else{
        write("NO");
    }
})();

(function main(){
    http://codeforces.com/problemset/problem/550/A

    var linea = readline();

    var regex = /(AB|BA)/g;

    var numeroMatches = 0;

    while(regex.test(linea) && numeroMatches <2){
        numeroMatches++;
    }
    if(numeroMatches == 2){
        write("YES");
    }else{
        write("NO");
    }
})();


Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.

/*
Problem from: http://codeforces.com/problemset/problem/296/D

D. Greg and Graph
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game:

The game consists of n steps.
On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex.
Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: .
Help Greg, print the value of the required sum before each step.

Input
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph.

Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j.

The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.

Output
Print n integers — the i-th number equals the required sum before the i-th step.

*/

var n = parseInt(readline());
var adjMat = [];
for(var i =0; i < n; i ++) {
    var temp = [];
    var line = readline().split(' ')
    for(var j =0; j <n; j ++) {
        temp.push(parseInt(line[j]));
    }
    adjMat.push(temp);
}

var verts = readline().split(' ')
var output = []
var ignored = []
for(var i = 0; i < n; i ++) {
    verts[i] = parseInt(verts[i]) - 1;
    output.push(0);
    ignored.push(false);
}
for (var r = n -1; r > -1; r--) {
    var toIgnore = verts[r];
    ignored[toIgnore] = true;

    for(var start=0; start<n; start++ ) {
        for(var end = 0; end<n; end++) {
            var update = adjMat[start][toIgnore] + adjMat[toIgnore][end];
            if(adjMat[start][end] > update) {
                adjMat[start][end] = update;
            }
            if(ignored[start] && ignored[end]) {
                output[r] += adjMat[start][end];
            }
        }
    }
}
print(output.join(' '));

var toInt = function(v){
	return parseInt(v);
}
var n = parseInt( readline() );
var m = [];
for(var i=0; i<n; i++){
	m.push(readline().split(' ').map(toInt) );
}
var x = readline().split(' ').map(toInt);
for(var i=0; i<n; i++){
	x[i]--;
}

function D(m){
	var sum = [];
	var h = [];
	for(var i=0; i<n; i++){
		sum[i] = 0;
		h[i] = false;
	}
	var min = Math.min;

	for(var k=n-1; k>=0; k--){
		var kk = x[k];
		h[kk] = true;
		for(var i=0; i<n; i++){
			for(var j=0; j<n; j++){
				var ij = m[i][j];
				var ikj = m[i][kk ] + m[ kk][j];
				var ij = ij<ikj?ij:ikj;
				m[i][j] = ij;
				if(h[i]&&h[j]){
					sum[k] += ij;
				}
			}
		}
	}
	return sum;
}

print( D(m).join(' ') );

/*
Problem from: http://codeforces.com/problemset/problem/296/D

D. Greg and Graph
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game:

The game consists of n steps.
On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex.
Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: .
Help Greg, print the value of the required sum before each step.

Input
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph.

Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j.

The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.

Output
Print n integers — the i-th number equals the required sum before the i-th step.

*/

var n = parseInt(readline());
var adjMat = [];
for(var i =0; i < n; i ++) {
    var temp = [];
    var line = readline().split(' ')
    for(var j =0; j <n; j ++) {
        temp.push(parseInt(line[j]));
    }
    adjMat.push(temp);
}

var verts = readline().split(' ')
var output = []
var ignored = []
for(var i = 0; i < n; i ++) {
    verts[i] = parseInt(verts[i]) - 1;
    output.push(0);
    ignored.push(false);
}
print(verts);
print(adjMat);
for (var r = n -1; r > -1; r--) {
    var toIgnore = verts[r];
    ignored[toIgnore] = true;

    for(var start=0; start<n; start++ ) {
        for(var end = 0; end<n; end++) {
            var update = adjMat[start][toIgnore] + adjMat[toIgnore][end];
            print(update);
            if(adjMat[start][end] > update) {
                adjMat[start][end] = update;
            }
            if(ignored[start] && ignored[end]) {
                output[r] += adjMat[start][end];
            }
        }
    }
}
print(output.join(' '));

/*
Problem from: http://codeforces.com/problemset/problem/296/D

D. Greg and Graph
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game:

The game consists of n steps.
On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex.
Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: .
Help Greg, print the value of the required sum before each step.

Input
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph.

Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j.

The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.

Output
Print n integers — the i-th number equals the required sum before the i-th step.

*/

var n = parseInt(readline());
var adjMat = [];
for(var i =0; i < n; i ++) {
    var temp = [];
    var line = readline().split(' ')
    for(var j =0; j <n; j ++) {
        temp.push(parseInt(line[j]));
    }
    adjMat.push(temp);
}

var verts = readline().split(' ')
var output = []
var ignored = []
for(var i = 0; i < n; i ++) {
    verts[i] = parseInt(verts[i]) - 1;
    output.push(0);
    ignored.push(false);
}

for (var r = n -1; r > -1; r--) {
    var toIgnore = verts[r];
    ignored[toIgnore] = true;

    for(var start=0; start<n; start++ ) {
        for(var end = 0; end<n; end++) {
            var update = adjMat[start][r] + adjMat[r][end];
            if(adjMat[start][end] > update) {
                adjMat[start][end] = update;
            }
            if(ignored[start] && ignored[end]) {
                output[r] += adjMat[start][end];
            }
        }
    }
}
print(output.join(' '));

var toInt = function(v){
	return parseInt(v);
}
var n = parseInt( readline() );
var m = [];
for(var i=0; i<n; i++){
	m.push( readline().split(' ').map(toInt) );
}
var x = readline().split(' ').map(toInt);

function sumD(){

	var sum = [];
	for(var i=0; i<n; i++){
		sum[i] = 0;
	}

	var h = [];
	for(var k=n-1; k>=0; k--){
		var kk = x[k];
		h[kk] = true;
		for(var i=0; i<n; i++){
			for(var j=0; j<n; j++){
				m[i][j] = Math.min(m[i][j], m[i][ x[k] ] + m[ x[k] ][j]);
			}
		}
		for(var i=0; i<n; i++){
			if(h[i]){
				for(var j=0; j<n; j++){
					if(h[j]){
						sum[k]+=m[i][j];
					}
				}
			}
		}
	}

	return sum;
}

for(var i=0; i<n; i++){
	x[i]--;
}

var sum = sumD();
print( sum.join() );

var toInt = function(v){
	return parseInt(v);
}
var n = parseInt( readline() );
var m = [];
for(var i=0; i<n; i++){
	m.push( readline().split(' ').map(toInt) );
}
var x = readline().split(' ').map(toInt);

function sumD(){

	var sum = [];
	for(var i=0; i<n; i++){
		sum[i] = 0;
	}

	var h = [];
	for(var k=0; k<n; k++){
		var kk = x[k];
		h[kk] = true;
		for(var i=0; i<n; i++){
			for(var j=0; j<n; j++){
				m[i][j] = Math.min(m[i][j], m[i][ x[k] ] + m[ x[k] ][j]);
			}
		}
		for(var i=0; i<n; i++){
			if(h[i]){
				for(var j=0; j<n; j++){
					if(h[j]){
						sum[kk]+=m[i][j];
					}
				}
			}
		}
	}

	return sum;
}

for(var i=0; i<n; i++){
	x[i]--;
}

var sum = sumD();
sum.reverse().forEach(function(v){
	print(v)
});


Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 \leq |s| \leq 50$$$) consisting of lowercase English letters.

For each test case, print the final string in a single line.

NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(var j = 1; j <= n; j++){
        var answer = '';
        var k = lines[j].split('');
        for(var l = 0; l < k.length; l++){
            if(l % 2 === 0){
                if(k[l] == 'a'){
                    answer += 'b';
                }else if(k[l] != 'a'){
                    answer += 'a';
                }
            }else if(l % 2 == 1){
                if(k[l] == 'z'){
                    answer += 'y';
                }else if(k[l] != 'z'){
                    answer += 'z';
                }
            }
        }
        console.log(answer);
    }
});

process.stdin.resume();
process.stdin.setEncoding("utf8");
let standardInputString = "";
let currentLine = 0;
function readLine() {
  return standardInputString[currentLine++];
}
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function main() {
  const numArray = (a) => a.split(" ").map((line) => +line),
    cl = console.log,
    rl = readLine,
    tc = rl();

  for (let i = 0; i < tc; i++) {
    const ln2 = rl().split("");
    solution(ln2);
  }
  /************************Solution****************************************/
  function solution(str) {
    // cl(str);
    let answer = "";
    let chance = true;
    for (let i = 0; i < str.length; i++) {
      if (chance) {
        if (str[i] == "a") answer += "b";
        else answer += "a";
        chance = !chance;
      } else {
        if (str[i] == "z") answer += "y";
        else answer += "z";
        chance = !chance;
      }
    }
    cl(answer);
  }
}

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const s = readLine();

        const res = a(s);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

function readLine() {
        return data[currentLine++];
}

function a(s){
    let finalString = '';
    let first = 97;
    let last = 122;
    for(let i = 0 ; i < s.length ; i++){
        let ascii = s[i].charCodeAt(0);
        if(i % 2 === 0){
            //alice turn
            if(ascii !== first){
                finalString += String.fromCharCode(first);
            } else {
                finalString += String.fromCharCode(first + 1);
            }
        } else {
            //Bob turn
            if(ascii !== last){
                finalString += String.fromCharCode(last);
            } else{
                finalString += String.fromCharCode(last - 1);
            }
        }
    }
    return finalString;
}

module.exports = a;

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

const calculate = s => {
  const result = []
  ;[...s].forEach((v, index) => {
    const code = v.charCodeAt()
    if (index % 2 === 0) {
      if (code === 97) {
        result.push(String.fromCharCode(code + 1))
      } else {
        result.push(String.fromCharCode(97))
      }
    } else {
      if (code === 122) {
        result.push(String.fromCharCode(code - 1))
      } else {
        result.push(String.fromCharCode(122))
      }
    }
  })
  return result.join('')
}

let index = -1
let maxRound = 0
let round = 0

let s
let answer = []

readline.on('line', line => {
  if (index === -1) {
    maxRound = Number(line)
    index = 0
  } else {
    s = line
    answer.push(calculate(s))
    round++
    if (round === maxRound) {
      readline.close()
      console.log(answer.join('\n'))
      return
    }

    index++
  }
})

// chainNumberList, cList, aList, bList
// console.log(calculate(4, [3, 4, 3, 3], [-1, 1, 2, 2], [-1, 2, 2, 3]))

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 gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function main() {
	let t = +readLine();
	while (t--) {
		const str = readLine();
		const result = [];
		let flag = true;
		for (let c of str) {
			if (flag) {
				if (c === 'a') result.push('b');
				else {
					result.push('a');
				}
				flag = false;
			} else {
				if (c === 'z') result.push('y');
				else {
					result.push('z');
				}
				flag = true;
			}
		}
		console.log(result.join(''));
	}
}

const processData = (lines) => {
    const n = +lines[0]
    for (let i=0; i<n; i++) {
        const a = lines[i+1].split('')
        for (let j=0; j<a.length; j++) {
            if (j%2 === 0) {
                a[j] = a[j] === 'a' ? 'b' : 'a'
            } else {
                a[j] = a[j] === 'z' ? 'y' : 'z'
            }

        }
        console.log(a.join(''))
    }
}

let i = []
process.stdin.on('data', c => i.push(c))
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.join('').split(EOL) /*your input text, split by lines*/
    processData(lines)
})

'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 array = readline().split('');
        var anwer = []
        for (var i = 0; i < array.length; i++) {
            // console.log(array[i])
            if(i % 2 ===0 && array[i] ==='a') anwer.push('b')
            if(i % 2 ===0 && array[i] !=='a') anwer.push('a')
            if(i % 2 ===1 && array[i] !=='z') anwer.push('z')
            if(i % 2 ===1 && array[i] ==='z') anwer.push('y')
        }

        console.log(anwer.join(''))
        // console.log(array.join(''))

    })
}

//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 s = nextCharArray();
		for(var j = 0; j < s.length; j++){
			if(j % 2 == 0){
				if(s[j] == "a"){
					s[j] = "b";
				}else{
					s[j] = "a";
				}
			}else{
				if(s[j] == "z"){
					s[j] = "y";
				}else{
					s[j] = "z";
				}
			}
		}
		myout(myconv(s, 0));
	}
}


Guy-Manuel and Thomas have an array $$$a$$$ of $$$n$$$ integers [$$$a_1, a_2, \dots, a_n$$$]. In one step they can add $$$1$$$ to any element of the array. Formally, in one step they can choose any integer index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := a_i + 1$$$.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $$$a_1 + a_2 +$$$ $$$\dots$$$ $$$+ a_n \ne 0$$$ and $$$a_1 \cdot a_2 \cdot$$$ $$$\dots$$$ $$$\cdot a_n \ne 0$$$.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-100 \le a_i \le 100$$$) — elements of the array .

For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.

NoteIn the first test case, the sum is $$$0$$$. If we add $$$1$$$ to the first element, the array will be $$$[3,-1,-1]$$$, the sum will be equal to $$$1$$$ and the product will be equal to $$$3$$$.In the second test case, both product and sum are $$$0$$$. If we add $$$1$$$ to the second and the third element, the array will be $$$[-1,1,1,1]$$$, the sum will be equal to $$$2$$$ and the product will be equal to $$$-1$$$. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding $$$1$$$ twice to the first element the array will be $$$[2,-2,1]$$$, the sum will be $$$1$$$ and the product will be $$$-4$$$.

'use strict'

const readInts = () => {
  return readline().split(' ').map(num => parseInt(num))
}

const readInt = () => readInts()[0]

let t = readInt()

while (t --> 0) {
  const n = readInt()
  const arr = readInts()

  let ans = 0
  let sum = 0
  for (let i in arr) sum += arr[i]

  for (let i in arr) {
    if (!arr[i]) {
      arr[i] ++
      ans ++
      sum ++
    }
  }

  if (!sum) {
    for (let i in arr) {
        if (arr[i] + 1 !== 0) {
            arr[i] ++
            ans ++
            break
        }
    }
  }

  print(ans)
}

'use strict'

const problem = (n, a) => {
    let r = 0, s = 0
    for (let i = 0; i < n; i++) {
        if (a[i] === 0) { r++; s++ }
        else s += a[i]
    }
    return r + !s
}
let t = +readline()
while(t--) print(problem(+readline(), readline().split(' ').map(i => +i)))

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
//[no]param
//不明値:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
function myconv(i,no){switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}
function Main() {
    var t = myconv(next(),1);
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var N = myconv(next(),1);
        var list = myconv(next(),4);
        var count = 0;
        var sum = 0;
        for(var j = 0; j < N; j++){
            sum += list[j];
            if(list[j] == 0){
                count++;
                sum++;
            }
        }
        if(sum == 0){
            count++;
        }
        output[i] = count;
    }
    myout(myconv(output,9));
}

function readNum() {
  return Number(readline());
}
function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = readNum();
  for (var i = 0; i < testCasesNum; i++) {
    var len = readNum();
    var arr = readNumArray();
    var zeros = 0;
    var sum = 0;
    for (var j = 0; j < len; j++) {
      sum += arr[j];
      if (arr[j] === 0) {
        zeros++;
      }
    }
    print(sum + zeros === 0 ? zeros + 1 : zeros);
  }
}
main()

var n=Number(readline());
for(var i=0;i<n;i++){
	var m=Number(readline());
	arr=readline().split(" ");
	var sum=0;
	var prod=0;
	for(var j=0;j<m;j++){
       sum+=Number(arr[j]);
       	if(Number(arr[j])===0)
       		prod+=1;
	}
	var nn=prod+sum;
	if(nn===0){
		print(prod+1);
	}
	else
		print(prod);
}
//balda solve hoyna kno
//bal chal problem amar

'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 readALine() {
    return inputString[currentLine++];
}

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

function stringArrayToBigInts(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( BigInt(array[i]) );
    }
    return result;
}

function sumOfAllElementsInArray(arr) {
    var result = 0;
    for( var i = 0; i < arr.length; i++ ) {
        result += arr[i];
    }
    return result;
}

function productOfAllElementsInArray(arr) {
    var result = 1;
    for( var i = 0; i < arr.length; i++ ) {
        result *= arr[i];
    }
    return result;
}

function maxOfElementsInArray(arr) {
    var result = 0;
    for( var i = 0; i < arr.length; i++ ) {
        if( arr[i] > result ) {
            result = arr[i];
        }
    }
    return result;
}

// ======================================================
// A. Non-zero
// http://codeforces.com/contest/1300/problem/A
// ======================================================

function findNumberOfZeros(arr) {
    var result = 0;
    for( var i = 0; i < arr.length; i++ ) {
        if( arr[i] === 0 ) {
            result += 1;
        }
    }
    return result;
}

function convertZeros(arr) {
    for( var i = 0; i < arr.length; i++ ) {
        if( arr[i] === 0 ) {
            arr[i] = 1;
        }
    }
    return arr;
}

function doIt( arr ) {
    var result = 0;
    var arr2 = arr;
    var extra = 0;

    var noz = findNumberOfZeros(arr);
    if( noz !== 0 ) {
        result = noz;
        arr2 = convertZeros(arr);
    }

    var sum = sumOfAllElementsInArray(arr2);
    if( sum == 0 ) {
        result = result + 1;
    }
    return result;
}

function main() {

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

process.stdin.resume();
process.stdin.setEncoding('utf-8')
let inputString = '';
let currentLine = 0;
process.stdin.on('data', input => { inputString += input; })
process.stdin.on('end', _ => { inputString = inputString.split('\n'); main(); })
const readline = () => { return inputString[currentLine++] }

function main() {
  const t = parseInt(readline());
  for (let i = 0; i < t; i++) {
    const n = parseInt(readline());
    const numbers = readline().split(' ').map(x => parseInt(x));
    let result = 0;
    let sum = 0;

    for (const number of numbers) {
      if (number === 0) {
        result++;
        sum++;
      } else {
        sum += number;
      }
    }

    if (sum === 0) {
      result++;
    }

    console.log(result);
  }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8')
let inputString = '';
let currentLine = 0;
process.stdin.on('data', input => { inputString += input; })
process.stdin.on('end', _ => { inputString = inputString.split('\n'); main(); })
const readline = () => { return inputString[currentLine++] }

function main() {
  const t = parseInt(readline());
  for (let i = 0; i < t; i++) {
    const n = parseInt(readline());
    let result = 0;
    let sum = 0;
    readline().split(' ').forEach(x => {
      const number = parseInt(x)
      if (number === 0) {
        result++;
        sum++;
      } else {
        sum += number;
      }
    });

    console.log((sum === 0) ? result + 1 : result);
  }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8')
let inputString = '';
let currentLine = 0;
process.stdin.on('data', input => { inputString += input; })
process.stdin.on('end', _ => { inputString = inputString.split('\n'); main(); })
const readline = () => { return inputString[currentLine++] }

function main() {
  const t = parseInt(readline());
  for (let i = 0; i < t; i++) {
    const n = parseInt(readline());
    const numbers = readline().split(' ').map(x => parseInt(x));
    let result = 0;

    for (const number of numbers) {
      if (number === 0) {
        result++;
      }
    }

    let sum = 0;
    for (const number of numbers) {
      if (number === 0) {
        sum++;
      } else {
        sum += number;
      }
    }

    if (sum === 0) {
      result++;
    }

    console.log(result);
  }
}

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 === 1) {
    c++;
    return;
  }

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

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 0) {
      arr[i] = 1;
      ans++;
    }

    sum += arr[i];
  }

  console.log(sum ? ans : ans + 1);
  c++;
});

rl.on('close', () => {

});

const calc = (d, x) => Math.ceil( d / (x + 1) + x)

const sum = arr => arr.reduce((r, x) => r+x, 0)
const mulAgr = arr => arr.reduce((r, x) => r*x, 1)

const processData = (lines) => {
  const num = +lines[0]

  for (let j=0; j<num; j++){
    const numsLine = lines[j*2+2].split(' ').map(x => +x)

    const sumOfLine = sum(numsLine)
    let minOps = 0
    if (sumOfLine === 0) {
      minOps = 1
    }
    let mulOps = 0
    for (const num of numsLine) {
      if (num === 0) {
        mulOps++
      }
    }
    const nonZeroArr = numsLine.map(x => x === 0 ? 1 : x)
    if (sum(nonZeroArr) === 0) {
      mulOps++
    }
    if (mulOps > minOps) {
      console.log(mulOps)
    } else {
      console.log(minOps)
    }
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

'use strict';

const { createInterface } = require('readline');
const rl = createInterface({
  input: process.stdin,
  crlfDelay: Infinity
});

const lines = [];
let nextLine = 0;
rl.on('line', (line) => {
  lines.push(line);
});

rl.on('close', () => {
  main();
});

function readline() {
  return lines[nextLine++];
}

function solve(arr) {
  const sum = arr.reduce((a, b) => a + b, 0);
  const num0 = arr.reduce((acc, cur) => {
    if (cur === 0) {
      acc++;
    }
    return acc;
  }, 0);

  return (sum === -num0) ? num0 + 1 : num0;
}

function main() {
  const t = parseInt(readline());
  // console.log({t});
  for(let i = 0; i < t; i++) {
    readline();
    const arr = readline().split(' ').map(Number);
    const res = solve(arr);
    console.log(res);
  }
}

var t, n, x
t = readline()
while(t--) {
    n = readline()
    x = readline().split(" ")
    var sum = 0;
    var zer = 0;
    for(i = 0; i < n; i++) {
        sum += parseInt(x[i]);
        if (parseInt(x[i]) === 0) zer++;
    }

    if (sum + zer === 0)
        print(zer + 1)
    else
        print(zer)
}

var n=Number(readline());
for(var i=0;i<n;i++){
	var m=Number(readline());
	arr=readline().split(" ");
	var sum=0;
	var prod=0;
	for(var j=0;j<m;j++){
       sum+=Number(arr[j]);
       	if(Number(arr[j])===0)
       		prod+=1;
	}
	if(prod===0 && (sum>0 || sum<0))
		print(0);
	else if(prod===0 && sum===0)
	print(1);
	else if(prod-sum===0){
		print(prod+1);
	}
	else{
		if(sum+prod===0)
			print(prod+1);
		else
			print(prod);
	}
}
//balda solve hoyna kno
//bal chal problem amar

var n=Number(readline());
for(var i=0;i<n;i++){
	var m=Number(readline());
	arr=readline().split(" ");
	var sum=0;
	var prod=0;
	for(var j=0;j<m;j++){
       sum+=Number(arr[j]);
       	if(Number(arr[j])===0)
       		prod+=1;
	}
	if(prod===0 && (sum>0 || sum<0))
		print(0);
	else if(prod===0 && sum===0)
	print(1);
	else if(prod-sum===0){
		print(prod+1);
	}
	else{
		if(sum+prod===0)
			print(prod+1)
		else
			print(prod);
	}
}
//balda solve hoyna kno
//bal chal problem amar

var n=Number(readline());
for(var i=0;i<n;i++){
	var m=Number(readline());
	arr=readline().split(" ");
	var sum=0;
	var prod=0;
	for(var j=0;j<m;j++){
       sum+=Number(arr[j]);
       	if(Number(arr[j])===0)
       		prod+=1;
	}
	if(prod===0 && (sum>0 || sum<0))
		print(0);
	else if(prod===0 && sum===0)
	print(1);
	else if(prod-sum===0){
		print(prod+1);
	}
	else
		print(Math.min(prod));
}
//balda solve hoyna kno
//bal chal problem amar

var n=Number(readline());
for(var i=0;i<n;i++){
	var m=Number(readline());
	arr=readline().split(" ");
	var sum=0;
	var prod=0;
	for(var j=0;j<m;j++){
       sum+=Number(arr[j]);
       	if(Number(arr[j])===0)
       		prod+=1;
	}
	if(prod===0 && (sum>0 || sum<0))
		print(0);
	else if(prod===0 && sum===0)
	print(1);
	else if(prod-sum===0){
		print(prod+1);
	}
	else
		print(Math.min(prod,sum));
}
//balda solve hoyna kno
//bal chal problem amar


The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 × 2 square, such that from the four letters of this square you can make word "face". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.

The first line contains two space-separated integers, n and m (1 ≤ n, m ≤ 50) — the height and the width of the image, respectively. Next n lines define the image. Each line contains m lowercase Latin letters.

In the single line print the number of faces on the image.

NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column:   In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown:   In the fourth sample the image has no faces on it.

var input = readline().split(" "), n = +input[0], m = +input[1], field = [];
for(i = 0; i < n; i++){
	field.push(readline().split(""))
}
var cnt = 0, face = [];

for(i = 0; i < n-1; i++){
	for(j = 0; j < m-1; j++){
		face[0] = field[i][j];
		face[1] = field[i][j+1];
		face[2] = field[i+1][j];
		face[3] = field[i+1][j+1];
		face.sort();
		if(face.join("") == "acef"){
			cnt++;
		}
	}
}

write(cnt);

(function main() {
  var line1 = readline().split(' ');
  var res = [];
  var face='face';

  for (var i=0; i < line1[0]; i++){
      res[i] = readline();
  }
  var count=0;
  for (var i=0; i < res.length - 1; i++) {
    for (var j=0; j < res[i].length -1; j++) {
      face='face';
      var face1 = face.replace(new RegExp(res[i][j]), '').replace(new RegExp(res[i+1][j]), '').replace(new RegExp(res[i][j+1]), '').replace(new RegExp(res[i+1][j+1]), '');
      if (face1.length == 0){
        count +=1;
      }
    }
  }

  print(count);
})();

function ProblemSolver() {
    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;
    this.CLEAR_ARRAY_PER_CASE = false;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , k , l ;
        res = 0 ;
        for( i = 0 ; i < this.n ; i++ ) {
        	for( j = 0 ; j < this.m ; j++ ) {
        		temp = [] ;
        		for( k = i ; k < Math.min( i + 2 , this.n ) ; k++ ) {
        			for( l = j ; l < Math.min( j + 2 , this.m ) ; l++ ) {
        				temp.push( this.arr[ k ].charAt( l ) ) ;
        			}
        		}
        		temp = temp.sort( function( le , ri ) { return le.localeCompare( ri ) ; } ) ;
        		temp = temp.join( '' ) ;
        		if( temp == 'acef' ) {
        			res++ ;
        		}
        	}
        }
        print( res );
    };

    this.init = function() {
        this.lim1 = 100010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            this.m = irObj.nextInt();
            this.arr = [] ;
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr.push( irObj.nextString() ) ;
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

    this.clearArraysPerCase = function() {
        var i;
        this.arr = new Array();
        this.adjList = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 );
            this.adjList.push( new Array() );
        }
    };

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    };

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adjList = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( "" );
            this.vis.push( 0 );
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.adjList.push( new Array() );
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() );
            this.done.push( new Array() );
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 );
                this.done[ i ].push( 0 );
            }
        }
    };

    this.init();
}

function InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine;
        while( true ) {
            try {
                singleLine = readline();
                if( singleLine == null ) {
                    break;
                }
            }
            catch( ex ) {
                break;
            }
            this.allLines.push( singleLine );
        }
    };

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    };

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    };

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    };

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString );
                currentString = "";
            }
            else {
                currentString += data[ i ];
            }
        }
        if( currentString != "" ) {
            this.allLines.push( currentString );
        }
    };

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            res = "";
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++;
            this.currrentCharacterIndex = 0;
            return res;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( "No more tokens available!" );
            }
            startIdx = -1;
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i;
                    break;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
                continue;
            }
            res = "";
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );
                }
            }
            this.currrentCharacterIndex = endIdx;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            return res;
        }
    };

    this.nextInt = function() {
        return parseInt( this.next( 1 ) );
    };

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) );
    };

    this.nextString = function() {
        return this.next( 1 );
    };

    this.nextLine = function() {
        return this.next( 0 );
    };
}

function FileOutputHandler() {
    this.resultantStringArray = new Array();

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString );
    };

    this.clearPercase = function() {
        this.resultantStringArray = new Array();
    };

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

function CodeExecutioner() {
    this.irObj = new InputReader();
    this.psObj = new ProblemSolver();
    this.fohObj = new FileOutputHandler();

    this.runCases = function() {
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt();
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase();
                this.psObj.getInput( this.irObj );
                this.psObj.solveCase();
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase();
                hasMoreTestCases = this.psObj.getInput( this.irObj );
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase();
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );
        }
    };

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {
                    environmentType = 'local-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    };

    this.configureStreamsAndReadInput = function() {
        var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments );
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino();
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
    };

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

var line = readline().split(' ');
var N = line[0] - 0, M = line[1] - 0;
var mat = [];

for (var i = 0; i < N; ++i) {
    mat[i] = readline();
}

var ans = 0;
for (var i = 0; i + 1 < N; ++i) {
    for (var j = 0; j + 1 < M; ++j) {
        var s = "" + mat[i][j] + mat[i + 1][j] + mat[i][j + 1] + mat[i + 1][j + 1];

        if (s.indexOf('f') >= 0 && s.indexOf('a') >= 0 && s.indexOf('c') >= 0 && s.indexOf('e') >= 0) ++ans;
    }
}

print(ans + "\n");

var line = readline().split(' ');
var n = Number(line[0]),
	m = Number(line[1]);

var face = 'acef';

var a = [];
for (var i = 0; i < n; i++) {
	a.push(readline());
}

var ans = 0;

for (var i = 0; i < n - 1; i++) {
	for (var j = 0; j < m - 1; j++) {
		var b = [a[i][j], a[i+1][j], a[i+1][j+1], a[i][j+1]];
		b.sort();
		b = b.join('');
		if (b === face) {
			ans += 1;
		}
	}
}

print(ans);

var IN = readline().split(' '),
    n = IN[0],
    m = IN[1],
    OUT = 0;

if(n<2 || m<2){
    print(OUT);
    quit();
}

var INPUT = [];
for(var i=0; i<n; i++){
    var line = readline();
    INPUT[i] = [];
    for(var j=0; j<m; j++){
        INPUT[i][j] = line[j];
    }
}

var sum =0;
for(i=0; i<n-1; i++){
    for(j=0; j<m-1; j++){
        if(j===0){
            sum = getV(INPUT[i][j]);
            sum += getV(INPUT[i][j+1]);
            sum += getV(INPUT[i+1][j]);
            sum += getV(INPUT[i+1][j+1]);
        }else{
            sum -= getV(INPUT[i][j-1]);
            sum -= getV(INPUT[i+1][j-1]);
            sum += getV(INPUT[i][j+1]);
            sum += getV(INPUT[i+1][j+1]);
        }

        if(sum===15) OUT++;
    }
}

function getV(char){
    switch(char){
        case 'f':
            return 1;
        case 'a':
            return 2;
        case 'c':
            return 4;
        case 'e':
            return 8;
        default:
            return 0;
    }
}

print(OUT);
quit();

function isPartOfFace(item){
	return (item == "f" || item == "a" || item == "c" || item == "e");
}
function isDefined(item){
	return (item != undefined);
}

var input = readline().split(" "), n = +input[0], m = +input[1], field = [];
for(i = 0; i < n; i++){
	field.push(readline().split(""))
}
var faces = {};

for(i = 0; i < n; i++){
	for(j = 0; j < m; j++){
		if(isPartOfFace(field[i][j])){
			if(isDefined(field[i-1])){
				if(isDefined(field[i-1][j-1]) && isPartOfFace(field[i-1][j-1]) && isPartOfFace(field[i][j-1]) && isPartOfFace(field[i-1][j])){
					if(!(((i-1) + "," + (j-1)) in faces)){
						faces[(i-1 + "," + j-1)] = true;
					}
				}
				if(isDefined(field[i-1][j+1]) && isPartOfFace(field[i-1][j]) && isPartOfFace(field[i-1][j+1]) && isPartOfFace(field[i][j+1])){
					if(!(((i-1) + "," + j) in faces)){
						faces[((i-1) + "," + j)] = true;
					}
				}
			}
			if(isDefined(field[i+1])){
				if(isDefined(field[i+1][j-1]) && isPartOfFace(field[i+1][j-1]) && isPartOfFace(field[i][j-1]) && isPartOfFace(field[i+1][j])){
					if(!((i + "," + (j-1)) in faces)){
						faces[(i + "," + (j-1))] = true;
					}
				}
				if(isDefined(field[i+1][j+1]) && isPartOfFace(field[i+1][j]) && isPartOfFace(field[i+1][j+1]) && isPartOfFace(field[i][j+1])){
					if(!((i + "," + j) in faces)){
						faces[(i + "," + j)] = true;
					}
				}
			}
		}
	}
}

write(Object.keys(faces).length);

(function main() {
  var line1 = readline().split(' ');
  var res = [];
  var face='face';

  for (var i=0; i < line1[0]; i++){
      res[i] = readline();
  }
  var count=0;
  for (var i=0; i < res.length - 1; i++) {
    for (var j=0; j < res[i].length -1; j++) {
      if (face.indexOf(res[i][j]) == -1 ||
        face.indexOf(res[i+1][j]) == -1 ||
        face.indexOf(res[i][j+1]) == -1 ||
        face.indexOf(res[i+1][j+1]) == -1 ){
        break;
      } else {
        count +=1;
      }
    }
  }

  print(count);
})();

(function main() {
  var line1 = readline().split(' ');
  var res = [];
  var face='face';

  for (var i=0; i < line1[0]; i++){
      res[i] = readline();
  }
  var count=0;
  for (var i=0; i < res.length - 1; i++) {
    for (var j=0; j < res[i].length -1; j++) {
      if (face.indexOf(res[i][j]) == -1 ||
        face.indexOf(res[i+1][j]) == -1 ||
        face.indexOf(res[i][j+1]) == -1 ||
        face.indexOf(res[i+1][j+1]) == -1 ){
      } else {
        count +=1;
      }
    }
  }

  print(count);
})();

(function main() {
  var line1 = readline().split(' ');
  var res = [];
  var face='face';

  for (var i=0; i < line1[0]; i++){
      res[i] = readline();
  }
  var count=0;
  for (var i=0; i < res.length - 1; i++) {
    for (var j=0; j < res[i].length -1; j++) {
      face='face';
      face.replace(new RegExp(res[i][j]), '');
      face.replace(new RegExp(res[i+1][j]), '');
      face.replace(new RegExp(res[i][j+1]), '');
      face.replace(new RegExp(res[i+1][j+1]), '');
      if (face.length == 0){
        count +=1;
      }
    }
  }

  print(count);
})();

var line = readline().split(' ');
var N = line[0] - 0, M = line[1] - 0;
var mat = [];

for (var i = 0; i < N; ++i) {
    mat[i] = readline();
}

var ans = 0;
for (var i = 0; i + 1 < N; ++i) {
    for (var j = 0; j + 1 < M; ++j) {
        var s = "" + mat[i][j] + mat[i + 1][j] + mat[i][j + 1] + mat[i + 1][j + 1];
        if (s.indexOf('f') > 0 && s.indexOf('a') > 0 && s.indexOf('c') > 0 && s.indexOf('e') > 0) ++ans;
    }
}

print(ans + "\n");

var line = readline().split(' ');
var N = line[0] - 0, M = line[1] - 0;
var mat = [];

for (var i = 0; i < N; ++i) {
    mat[i] = readline();
}

var ans = 0;
for (var i = 0; i + 1 < N; ++i) {
    for (var j = 0; j + 1 < M; ++j) {
        var s = "" + mat[i][j] + mat[i + 1][j] + mat[i][j + 1] + mat[i + 1][j + 1];

print(s.indexOf('a'));
        if (s.indexOf('f') > 0 && s.indexOf('a') > 0 && s.indexOf('c') > 0 && s.indexOf('e') > 0) ++ans;
    }
}

print(ans + "\n");

var line = readline().split(' ');
var N = line[0] - 0, M = line[1] - 0;
var mat = [];

for (var i = 0; i < N; ++i) {
    mat[i] = readline();
}

var ans = 0;
for (var i = 0; i + 1 < N; ++i) {
    for (var j = 0; j + 1 < M; ++j) {
        var s = "" + mat[i][j] + mat[i + 1][j] + mat[i][j + 1] + mat[i + 1][j + 1];

        print(s);
        if (s.indexOf('f') > 0 && s.indexOf('a') > 0 && s.indexOf('c') > 0 && s.indexOf('e') > 0) ++ans;
    }
}

print(ans + "\n");