bool symmetric(TreeNode *left, TreeNode *right){
     if(left==NULL && right==NULL) return true;
     if(left==NULL || right==NULL) return false;
     if((left->val) != (right->val)) return false;
     return symmetric(left->right, right->left)
            &&symmetric(left->left, right->right);
 }
Exemple #2
0
		bool symmetric(TreeNode* first, TreeNode* second) {
			if (first == NULL && second == NULL) return true;
			if (first == NULL || second == NULL) return false;
			if (first->val != second->val) return false;

			return symmetric(first->left, second->right) && symmetric(first->right, second->left);
		}
Exemple #3
0
bool symmetric(struct TreeNode *lhs,struct TreeNode *rhs)
{
	if(lhs==NULL&&rhs==NULL)
		return true;
	else if(lhs!=NULL&&rhs!=NULL&&lhs->val==rhs->val)
		return symmetric(lhs->left,rhs->right)&&symmetric(lhs->right,rhs->left);
	else
		return false;
}
Exemple #4
0
//version 1 recursive
bool symmetric( struct TreeNode* left, struct TreeNode* right )
{
	if(!left && !right) 
		return true;
	else if(!left || !right) 
		return false;
	if(left->val != right->val) 
		return false;

	return symmetric(left->left, right->right) && symmetric(left->right, right->left);
}
Exemple #5
0
scoreAndLoc BoardThread::alphabeta(bool maximize, int alpha, int beta,
				   size_t depth, int justPlayed){
  recursionCount++;
  if (depth > 0 && memberOfAP(justPlayed))
    { return ((grid[justPlayed]=='R')?r_win:b_win); }

  if (depth == n) { return draw; }
  
  int max = -10;  int min = 10;  int loc = -1;

  //symmetry -> don't bother checking rhs
  bool s = symmetric();

  //Loop
  for(int i = ((n%2)?(n/2):((n/2) - 1)); i > -1; i--){
    if (depth == 0 && i%numThreads != id) { continue; }

    //Check i
    if (!(depth == 0 && i==0) &&
	alphabeta_helper(i, maximize, depth, max, min, loc, alpha, beta))
      { break; }

    if (s) {continue;}
    int j = n-i-1;

    if (alphabeta_helper(j, maximize, depth, max, min, loc, alpha, beta))
      { break; }

  }

  return scoreAndLoc((maximize?max:min), loc);

}
    bool symmetric(TreeNode *left, TreeNode *right) {
        if (left == NULL && right != NULL)
            return false;
        if (left != NULL && right == NULL)
            return false;
        if (left == NULL && right == NULL)
            return true;

        if (left->val != right->val)
            return false;

        bool lsym = symmetric(left->left, right->right);
        bool rsym = symmetric(left->right, right->left);

        return lsym && rsym;
    }
int main(){
	int a;
	printf("Digite um número: > ");
	scanf("%d",&a);
	printf("O simétrico de %d é %d\n",a,symmetric(a));
	return 0;
	}
Exemple #8
0
	Graph undirected(Graph g) {
		using ConstNode = typename Graph::ConstNode_t;

		Graph symm = symmetric(g);

		symm.eachEdges([&g, &symm](ConstNode begin, ConstNode end) {
			g.connect(g[begin.getName()], g[end.getName()], symm.getEdgeProperty(begin, end));
		});

		return g;
	}
Exemple #9
0
	std::set<typename Graph::ConstNode_t> stronglyConnectedComponent(
	        Graph const& g,
	        typename Graph::ConstNode_t const& vertex) {
		using Node = typename Graph::ConstNode_t;

		std::set<Node> verticesToCheck{vertex}, existPathToVertex{vertex},
		        existPathToVertexSym{vertex};

		while(!verticesToCheck.empty()) {
			auto currentVertex = *verticesToCheck.begin();
			verticesToCheck.erase(currentVertex);

			g.eachAdjacents(currentVertex,
			                [&existPathToVertex, &verticesToCheck](Node i) {
				                if(existPathToVertex.find(i) == existPathToVertex.end()) {
					                verticesToCheck.insert(i);
					                existPathToVertex.insert(i);
				                }
				            });
		}

		Graph sym       = symmetric(g);
		verticesToCheck = std::set<Node>{sym[vertex.getName()]};

		while(!verticesToCheck.empty()) {
			auto currentVertex = *verticesToCheck.begin();
			verticesToCheck.erase(currentVertex);

			sym.eachAdjacents(currentVertex,
			                  [&existPathToVertexSym, &verticesToCheck, &g](Node i) {
				                  if(existPathToVertexSym.find(i) == existPathToVertexSym.end()) {
					                  verticesToCheck.insert(i);
					                  existPathToVertexSym.insert(i);
				                  }
				              });
		}

		std::set<Node> existPathToVertexSymTemp, component;

		for(auto const& node : existPathToVertexSym) {
			existPathToVertexSymTemp.insert(g[node.getName()]);
		}

		std::set_intersection(existPathToVertex.begin(),
		                      existPathToVertex.end(),
		                      existPathToVertexSymTemp.begin(),
		                      existPathToVertexSymTemp.end(),
		                      std::inserter(component, component.begin()));

		return component;
	}
Exemple #10
0
	std::set<typename Graph::ConstNode_t> connectedComponent(
	        Graph const& g,
	        typename Graph::ConstNode_t const& vertex) {
		using Node = typename Graph::ConstNode_t;

		std::set<std::string> verticesToCheck{vertex.getName()}, component{vertex.getName()};

		Graph sym = symmetric(g);

		while(!verticesToCheck.empty()) {
			auto currentVertex = *verticesToCheck.begin();
			verticesToCheck.erase(currentVertex);

			g.eachAdjacents(g[currentVertex],
			                [&component, &verticesToCheck](Node i) {
				                std::string nodeName = i.getName();
				                if(component.find(nodeName) == component.end()) {
					                verticesToCheck.insert(nodeName);
					                component.insert(nodeName);
				                }
				            });

			sym.eachAdjacents(sym[currentVertex],
			                  [&component, &verticesToCheck, &g](Node i) {
				                  std::string nodeName = i.getName();
				                  if(component.find(nodeName) == component.end()) {
					                  verticesToCheck.insert(nodeName);
					                  component.insert(nodeName);
				                  }
				              });
		}

		std::set<Node> nodeComponent;

		for(auto const& nodeName : component) {
			nodeComponent.insert(g[nodeName]);
		}

		return nodeComponent;
	}
Exemple #11
0
 bool isSymmetric(TreeNode *root) {
     if (root == NULL) return true;
     return symmetric(root->left, root->right);
 }
void Foam::lduMatrix::operator-=(const lduMatrix& A)
{
    if (A.diagPtr_)
    {
        diag() -= A.diag();
    }

    if (symmetric() && A.symmetric())
    {
        upper() -= A.upper();
    }
    else if (symmetric() && A.asymmetric())
    {
        if (upperPtr_)
        {
            lower();
        }
        else
        {
            upper();
        }

        upper() -= A.upper();
        lower() -= A.lower();
    }
    else if (asymmetric() && A.symmetric())
    {
        if (A.upperPtr_)
        {
            lower() -= A.upper();
            upper() -= A.upper();
        }
        else
        {
            lower() -= A.lower();
            upper() -= A.lower();
        }

    }
    else if (asymmetric() && A.asymmetric())
    {
        lower() -= A.lower();
        upper() -= A.upper();
    }
    else if (diagonal())
    {
        if (A.upperPtr_)
        {
            upper() = -A.upper();
        }

        if (A.lowerPtr_)
        {
            lower() = -A.lower();
        }
    }
    else if (A.diagonal())
    {
    }
    else
    {
        if (debug > 1)
        {
            WarningIn("lduMatrix::operator-=(const lduMatrix& A)")
                << "Unknown matrix type combination" << nl
                << "    this :"
                << " diagonal:" << diagonal()
                << " symmetric:" << symmetric()
                << " asymmetric:" << asymmetric() << nl
                << "    A    :"
                << " diagonal:" << A.diagonal()
                << " symmetric:" << A.symmetric()
                << " asymmetric:" << A.asymmetric()
                << endl;
        }
    }
}
void Foam::BlockLduMatrix<Type>::AmulCore
(
    TypeField& Ax,
    const TypeField& x
) const
{
    typedef typename TypeCoeffField::scalarTypeField scalarTypeField;
    typedef typename TypeCoeffField::linearTypeField linearTypeField;
    typedef typename TypeCoeffField::squareTypeField squareTypeField;

    const unallocLabelList& u = lduAddr().upperAddr();
    const unallocLabelList& l = lduAddr().lowerAddr();

    const TypeCoeffField& Diag = this->diag();
    const TypeCoeffField& Upper = this->upper();

    // Create multiplication function object
    typename BlockCoeff<Type>::multiply mult;

    // Diagonal multiplication, no indirection
    multiply(Ax, Diag, x);

    // Lower multiplication

    if (symmetric())
    {
        if (Upper.activeType() == blockCoeffBase::SCALAR)
        {
            const scalarTypeField& activeUpper = Upper.asScalar();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                Ax[u[coeffI]] += mult(activeUpper[coeffI], x[l[coeffI]]);
            }
        }
        else if (Upper.activeType() == blockCoeffBase::LINEAR)
        {
            const linearTypeField& activeUpper = Upper.asLinear();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                Ax[u[coeffI]] += mult(activeUpper[coeffI], x[l[coeffI]]);
            }
        }
        else if (Upper.activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeUpper = Upper.asSquare();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                // Use transpose upper coefficient
                Ax[u[coeffI]] +=
                    mult(activeUpper[coeffI].T(), x[l[coeffI]]);
            }
        }
    }
    else // Asymmetric matrix
    {
        const TypeCoeffField& Lower = this->lower();

        if (Lower.activeType() == blockCoeffBase::SCALAR)
        {
            const scalarTypeField& activeLower = Lower.asScalar();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                Ax[u[coeffI]] += mult(activeLower[coeffI], x[l[coeffI]]);
            }
        }
        else if (Lower.activeType() == blockCoeffBase::LINEAR)
        {
            const linearTypeField& activeLower = Lower.asLinear();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                Ax[u[coeffI]] += mult(activeLower[coeffI], x[l[coeffI]]);
            }
        }
        else if (Lower.activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeLower = Lower.asSquare();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                Ax[u[coeffI]] += mult(activeLower[coeffI], x[l[coeffI]]);
            }
        }
    }


    // Upper multiplication

    if (Upper.activeType() == blockCoeffBase::SCALAR)
    {
        const scalarTypeField& activeUpper = Upper.asScalar();

        for (register label coeffI = 0; coeffI < u.size(); coeffI++)
        {
            Ax[l[coeffI]] += mult(activeUpper[coeffI], x[u[coeffI]]);
        }
    }
    else if (Upper.activeType() == blockCoeffBase::LINEAR)
    {
        const linearTypeField& activeUpper = Upper.asLinear();

        for (register label coeffI = 0; coeffI < u.size(); coeffI++)
        {
            Ax[l[coeffI]] += mult(activeUpper[coeffI], x[u[coeffI]]);
        }
    }
    else if (Upper.activeType() == blockCoeffBase::SQUARE)
    {
        const squareTypeField& activeUpper = Upper.asSquare();

        for (register label coeffI = 0; coeffI < u.size(); coeffI++)
        {
            Ax[l[coeffI]] += mult(activeUpper[coeffI], x[u[coeffI]]);
        }
    }
}
Exemple #14
0
static int squares_remaining(int row, int col)
{
        int rowsquares = N * (N - 2 * row);
        int n = (row == symmetric(row) ? 1 : 2) * (N - col + 1);
        return rowsquares > 0 ? n + rowsquares : n;
}
Exemple #15
0
		bool isSymmetric(TreeNode* root) {
			return symmetric(root, root);
		}
Exemple #16
0
bool isSymmetric( struct TreeNode * root )
{
	if(!root) 
		return true;
	return symmetric(root->left, root->right);
}
/***********************************************************************//**
 * @brief Test matrix allocation
 ***************************************************************************/
void TestGMatrixSparse::alloc_matrix(void)
{
    // Allocate zero matrix. The allocation should fail.
    test_try("Allocate zero matrix");
    try {
        GMatrixSparse test(0,0);
        test_try_failure("Expected GException::empty exception.");
    }
    catch (GException::empty &e) {
        test_try_success();
    }
    catch (std::exception &e) {
        test_try_failure(e);
    }

    // Setup a symmetric sparse matrix
    int size = 30;
    GMatrixSparse symmetric(size,size);
    for (int i = 0; i < size; i+=2) {
        for (int j = 0; j < size; j+=2) {
            symmetric(i,j) = 1.0+i+j;
        }
    }

    // Convert to GMatrix
    test_try("Test symmetric GMatrix conversion");
    try {
        GMatrix cnv_matrix        = GMatrix(symmetric);
        GMatrixSparse back_matrix = GMatrixSparse(cnv_matrix);
        test_assert((symmetric == back_matrix),
                    "Test symmetric GMatrixSparse - GMatrix conversion",
                    "Found:\n"+back_matrix.print()+"\nExpected:\n"+symmetric.print());
        test_try_success();
    }
    catch (GException::empty &e) {
        test_try_success();
    }
    catch (std::exception &e) {
        test_try_failure(e);
    }

    // Test GMatrix conversion
    test_try("Test GMatrix conversion");
    try {
        GMatrix       cnv_matrix  = GMatrix(m_test);
        GMatrixSparse back_matrix = GMatrixSparse(cnv_matrix);
        test_assert((m_test == back_matrix),
                    "Test GMatrixSparse - GMatrix conversion",
                    "Found:\n"+back_matrix.print()+"\nExpected:\n"+m_test.print());
        test_try_success();
    }
    catch (std::exception &e) {
        test_try_failure(e);
    }

    // Test GMatrixSparse <-> GMatrixSymmetric conversion
    test_try("Test GMatrixSymmetric conversion");
    try {
        GMatrixSymmetric cnv_sym  = GMatrixSymmetric(symmetric);
        GMatrixSparse    back_sym = GMatrixSparse(cnv_sym);
        test_assert((symmetric == back_sym),
                    "Test GMatrixSparse - GMatrixSymmetric conversion",
                    "Found:\n"+back_sym.print()+"\nExpected:\n"+symmetric.print());
        test_try_success();
    }
    catch (std::exception &e) {
        test_try_failure(e);
    }

    // Test invalid GMatrixSparse <-> GMatrixSymmetric conversion
    test_try("Test invalid GMatrixSymmetric conversion");
    try {
        GMatrixSymmetric bad_sym = GMatrixSymmetric(m_test);
        test_try_failure("Expected GException::matrix_not_symmetric exception.");
    }
    catch (GException::matrix_not_symmetric &e) {
        test_try_success();
    }
    catch (std::exception &e) {
        test_try_failure(e);
    }

    // Return
    return;
}
/*******************************************************************************
 * 
 * The main function.
 * 
 ******************************************************************************/
int main(int argc, char** argv) {
    if (argc <= 1) {
        printf("\n Please provide a filename as a command line argument.\n");
        exit(-1);
    }

    FILE *inputfile;
    int matrixOrder = 0, i = 0, j = 0, edges = 0;
    int** matrix;
    node* vertices;
    node* mergedArray;

    inputfile = fopen(argv[1], "r");

    if (inputfile == NULL) {
        printf("\nThere was an error in opening the file.\n");
        exit(-1);
    }

    //Read the number of elements.
    fscanf(inputfile, "%d", &matrixOrder);

    //Initialize the values of the pointers to NULL.
    matrix = (int**) malloc(matrixOrder * sizeof (int *));
    vertices = (node*) malloc(matrixOrder * sizeof (node));
    mergedArray = (node*) malloc(matrixOrder * sizeof (node));

    //Initialise to zero.
    for (i = 0; i < matrixOrder; i++) {
        matrix[i] = (int*) malloc(matrixOrder * sizeof (int));
        vertices[i].degree = 0;
        vertices[i].colour = 0;
    }

    //Read in the matrix from the input file.
    for (i = 0; i < matrixOrder; i++) {
        vertices[i].index = i;
        for (j = 0; j < matrixOrder; j++) {
            fscanf(inputfile, "%d", &matrix[i][j]);
        }
    }

    fclose(inputfile);

    //Ensure graph is undirected.
    symmetric(matrix, matrixOrder);

    //Calculate degrees
    for (i = 0; i < matrixOrder; i++) {
        for (j = 0; j < matrixOrder; j++) {
            if (matrix[i][j]) {
                vertices[i].degree++;
            }
        }
    }

    //DFS Algorithm:
    DFS(vertices, -1, 0, 1, matrix, matrixOrder);
    printOutput(vertices, matrix, matrixOrder, "DFS");

    //DFS Improved Algorithm:
    DFSimproved(vertices, matrix, matrixOrder);
    printOutput(vertices, matrix, matrixOrder, "DFS Improved");

    //Applying Merge Sort for the above Greedy-based Algorithm:
    mergeSort(vertices, 0, matrixOrder, mergedArray);
    greedyPartition(vertices, matrix, matrixOrder);
    printOutput(vertices, matrix, matrixOrder, "Greedy-based Algorithm");

    free(vertices);
    free(matrix);
    return (EXIT_SUCCESS);
}
Exemple #19
0
void Foam::lduMatrix::operator+=(const lduMatrix& A)
{
    if (A.diagPtr_)
    {
        diag() += A.diag();
    }

    if (symmetric() && A.symmetric())
    {
        upper() += A.upper();
    }
    else if (symmetric() && A.asymmetric())
    {
        if (upperPtr_)
        {
            lower();
        }
        else
        {
            upper();
        }

        upper() += A.upper();
        lower() += A.lower();
    }
    else if (asymmetric() && A.symmetric())
    {
        if (A.upperPtr_)
        {
            lower() += A.upper();
            upper() += A.upper();
        }
        else
        {
            lower() += A.lower();
            upper() += A.lower();
        }

    }
    else if (asymmetric() && A.asymmetric())
    {
        lower() += A.lower();
        upper() += A.upper();
    }
    else if (diagonal())
    {
        if (A.upperPtr_)
        {
            upper() = A.upper();
        }

        if (A.lowerPtr_)
        {
            lower() = A.lower();
        }
    }
    else if (A.diagonal())
    {
    }
    else
    {
        if (debug > 1)
        {
            WarningIn("lduMatrix::operator+=(const lduMatrix& A)")
                << "Unknown matrix type combination"
                << endl;
        }
    }
}
Exemple #20
0
static void numbergrid(int row, int col, int low_clue, int high_clue) 
{
        if (row == 2 && low_clue == 1 && !ALLBLOT) return;
        {
                static unsigned long count = 0;
	        if (K > 0 && ++count >= K) {
                        printf("At %d, %d:\n", row, col);
                        show(); 
                        count = 0;
                }
        }
        if (high_clue - low_clue + 1 > squares_remaining(row, col)) {
                return;
        }
        if (col > N) {
                numbergrid(row + 1, 1, low_clue, high_clue);
        } else {
                int srow, scol, snum;
                srow = symmetric(row);
                scol = symmetric(col);
                snum = srow + 1;
                if (row > srow) {
                        NUMBERUP(row, 1, N);
                        if (low_clue == high_clue + 1) show();
                } else if (row == symmetric(row) && col > symmetric(col)) {
                        /*printf("Numbergrid up:\n"); show();*/
                        NUMBERUP(row, col, N);
                        NUMBERUP(snum, 1, col - 2);
                        if (low_clue == high_clue + 1) show();
                } else {
                        int newhi;
                        if (across[low_clue] 
                            && (row != firstrow || col != firstcol) 
                            && !across[grid[row][col-1]]
                            && !down[grid[row-1][col]] /* no 1-letter words */
                            && (newhi = high_clue,
                                blot(srow, scol), 
                                blotted(snum, scol) 
                                ? 1   /* not blank; no numbergrid issues */
                                : blotted(snum, scol - 1) 
                                ? across[newhi] && down[newhi] /* OK to number */
                                ? (grid[snum][scol] = newhi--, 1)
                                : 0  /* must number, but newhi won't work here */
                                : !across[newhi] && down[newhi] /* OK to number */
                                ? (grid[snum][scol] = newhi--, 1)
                                : 0  /* must number, but newhi won't work here */
                                    )
                            && (MINWORD <= 2 || !shortwords(row, col)) 
                                ) {
                                blot(row, col);
                                numbergrid(row, col + 1, low_clue, newhi);
                                {
                                        if (!blotted(snum, scol))
                                        	blank(snum, scol, BLANK);
                                }
                        }
                        if (row > firstrow || col >= firstcol) {
                                if ((newhi = high_clue,
                                     blank(srow, scol, BLANK),
                                     blotted(snum, scol) 
                                     ? 1   /* not blank; no numbergrid issues */
                                     : blotted(snum, scol - 1) 
                                     ? across[newhi] && !down[newhi] /* OK to number */
                                     ? (blank(snum, scol, newhi--), 1)
                                     : 0  /* must number, but newhi won't work here */
                                     : 1 /* no blot to left, therefore no number needed */
                                            )) {
                                        if (numberable(row, col, low_clue)
                                            && low_clue <= high_clue) {
                                                blank(row, col, low_clue);
                                                numbergrid(row,
                                                           col + 1,
                                                           low_clue + 1,
                                                           newhi);
                                        } else if (!numberable(row, col, ANY)) {
                                                blank(row, col, BLANK);
                                                numbergrid(row,
                                                           col + 1,
                                                           low_clue,
                                                           newhi);
                                        }
                                        { if (!blotted(snum, scol))
                                                        blank(snum,
                                                              scol,
                                                              BLANK); }
                                }
                        }
                        grid[row][col] = grid[srow][scol] = UNKNOWN;
                }
        }
}
void Foam::BlockLduMatrix<Type>::segregateB
(
    TypeField& sMul,
    const TypeField& x
) const
{
    typedef typename TypeCoeffField::linearType linearType;
    typedef typename TypeCoeffField::squareType squareType;

    typedef typename TypeCoeffField::linearTypeField linearTypeField;
    typedef typename TypeCoeffField::squareTypeField squareTypeField;

    const unallocLabelList& u = lduAddr().upperAddr();
    const unallocLabelList& l = lduAddr().lowerAddr();

    // Diagonal multiplication
    if (thereIsDiag())
    {
        if (diag().activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeDiag = this->diag().asSquare();
            linearTypeField lf(activeDiag.size());
            squareTypeField sf(activeDiag.size());

            // Expand and contract
            contractLinear(lf, activeDiag);
            expandLinear(sf, lf);

            sMul -= (activeDiag - sf) & x;
        }
    }

    // Lower multiplication

    if (thereIsLower())
    {
        if (lower().activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeLower = this->lower().asSquare();

            // Auxiliary variables used in expand/contract
            linearType lt;
            squareType st;

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                contractLinear(lt, activeLower[coeffI]);
                expandLinear(st, lt);

                sMul[u[coeffI]] -= (activeLower[coeffI] - st) & x[l[coeffI]];
            }
        }
    }

    // Upper multiplication

    if (thereIsUpper())
    {
        if (upper().activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeUpper = this->upper().asSquare();

            // Auxiliary variables used in expand/contract
            linearType lt;
            squareType st;

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                contractLinear(lt, activeUpper[coeffI]);
                expandLinear(st, lt);

                sMul[l[coeffI]] -= (activeUpper[coeffI] - st) & x[u[coeffI]];
            }

            // If the matrix is symmetric, the lower triangular product
            // is also needed
            if (symmetric())
            {
                for (register label coeffI = 0; coeffI < u.size(); coeffI++)
                {
                    // Use transpose upper coefficient
                    contractLinear(lt, activeUpper[coeffI]);
                    expandLinear(st, lt);
                    sMul[u[coeffI]] -=
                        (activeUpper[coeffI].T() - st) & x[l[coeffI]];
                }
            }
        }
    }
}
Exemple #22
0
void Foam::lduMatrix::operator-=(const lduMatrix& A)
{
    if (A.diagPtr_)
    {
        diag() -= A.diag();
    }

    if (symmetric() && A.symmetric())
    {
        upper() -= A.upper();
    }
    else if (symmetric() && A.asymmetric())
    {
        if (upperPtr_)
        {
            lower();
        }
        else
        {
            upper();
        }

        upper() -= A.upper();
        lower() -= A.lower();
    }
    else if (asymmetric() && A.symmetric())
    {
        if (A.upperPtr_)
        {
            lower() -= A.upper();
            upper() -= A.upper();
        }
        else
        {
            lower() -= A.lower();
            upper() -= A.lower();
        }

    }
    else if (asymmetric() && A.asymmetric())
    {
        lower() -= A.lower();
        upper() -= A.upper();
    }
    else if (diagonal())
    {
        if (A.upperPtr_)
        {
            upper() = -A.upper();
        }

        if (A.lowerPtr_)
        {
            lower() = -A.lower();
        }
    }
    else if (A.diagonal())
    {
    }
    else
    {
        FatalErrorIn("lduMatrix::operator-=(const lduMatrix& A)")
            << "Unknown matrix type combination"
            << abort(FatalError);
    }
}
	bool symmetric(TreeNode* l, TreeNode* r) {
		if(!l && !r) return true;
		if(!l || !r) return false;
		return l->val == r->val && symmetric(l->left, r->right) && symmetric(l->right, r->left);
	}
Exemple #24
0
scoreAndLoc Board_AB::alphabeta(bool maximize, char alpha, char beta,
				num depth, num x){
  recursionCount++;

  char score = -10;
  num loc = 0;
  char alphaOrig = alpha;
  if (retrieveSmart(score, loc, alpha, beta)){ return scoreAndLoc(score,loc); }

  if (depth >= 2*k-1){
    if (memberOfAP(x)){
      char sign = (maximize?1:-1);
      char result = sign * ((!maximize)?R_WIN:B_WIN);
      return scoreAndLoc(result, x);
    }
    if (depth == n) { return draw; }
  }

  /*
  num& killer1 = killers[depth].first;
  if (killer1 != n && alphabeta_helper(killer1, maximize, depth, score,
				       loc, alpha, beta)){
    return scoreAndLoc(score,loc);
  }
  num killer2 = killers[depth].second;
  if (killer2 != n && alphabeta_helper(killer2, maximize, depth, score,
				       loc, alpha, beta)){
    return scoreAndLoc(score,loc);
  }
  */

  //symmetry -> don't bother checking rhs
  bool s = symmetric();
  bool firstChild = true;

  for(int i = ((n%2)?(n/2):((n/2) - 1)); i > -1; i--){
    if (//i != killer1 && i != killer2 &&
	alphabeta_helper(i, maximize, depth, score, loc, alpha, beta,firstChild))
      {
	//killers[depth].second = killer1;
	//killer1 = i;
	break;
      }
    
    if (s) {continue;}
    
    int j = n-i-1;
    if (//j != killer1 && j != killer2 &&
	alphabeta_helper(j, maximize, depth, score, loc, alpha, beta,firstChild))
      {
	//killers[depth].second = killer1;
	//killer1 = i;
	break;
      }
    
  }

  storeSmart(score, loc, alphaOrig, beta);
  if (depth == 0) {
    cout << "States hit: " << recursionCount << endl;
    cout << "Table size: " << tableSize << endl;
  }
  return scoreAndLoc(score, loc);
}
Foam::tmp<Foam::Field<Type> >
Foam::BlockLduMatrix<Type>::decoupledH(const Field<Type>& x) const
{
    typedef typename TypeCoeffField::scalarTypeField scalarTypeField;
    typedef typename TypeCoeffField::linearTypeField linearTypeField;

    // Create result
    tmp<Field<Type> > tresult
    (
        new Field<Type>(lduAddr().size(), pTraits<Type>::zero)
    );
    Field<Type>& result = tresult();

    const unallocLabelList& u = lduAddr().upperAddr();
    const unallocLabelList& l = lduAddr().lowerAddr();

    const TypeCoeffField& Upper = this->upper();

    // Create multiplication function object
    typename BlockCoeff<Type>::multiply mult;

    // Lower multiplication

    if (symmetric())
    {
        if (Upper.activeType() == blockCoeffBase::SCALAR)
        {
            const scalarTypeField& activeUpper = Upper.asScalar();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                result[u[coeffI]] -= mult(activeUpper[coeffI], x[l[coeffI]]);
            }
        }
        else if (Upper.activeType() == blockCoeffBase::LINEAR)
        {
            const linearTypeField& activeUpper = Upper.asLinear();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                result[u[coeffI]] -= mult(activeUpper[coeffI], x[l[coeffI]]);
            }
        }
    }
    else // Asymmetric matrix
    {
        const TypeCoeffField& Lower = this->lower();

        if (Lower.activeType() == blockCoeffBase::SCALAR)
        {
            const scalarTypeField& activeLower = Lower.asScalar();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                result[u[coeffI]] -= mult(activeLower[coeffI], x[l[coeffI]]);
            }
        }
        else if (Lower.activeType() == blockCoeffBase::LINEAR)
        {
            const linearTypeField& activeLower = Lower.asLinear();

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                result[u[coeffI]] -= mult(activeLower[coeffI], x[l[coeffI]]);
            }
        }
    }


    // Upper multiplication

    if (Upper.activeType() == blockCoeffBase::SCALAR)
    {
        const scalarTypeField& activeUpper = Upper.asScalar();

        for (register label coeffI = 0; coeffI < u.size(); coeffI++)
        {
            result[l[coeffI]] -= mult(activeUpper[coeffI], x[u[coeffI]]);
        }
    }
    else if (Upper.activeType() == blockCoeffBase::LINEAR)
    {
        const linearTypeField& activeUpper = Upper.asLinear();

        for (register label coeffI = 0; coeffI < u.size(); coeffI++)
        {
            result[l[coeffI]] -= mult(activeUpper[coeffI], x[u[coeffI]]);
        }
    }

    return tresult;
}