void IOWrapper::OutputBestHypo(const Hypothesis *hypo, long /*translationId*/, char reportSegmentation, bool reportAllFactors) { if (hypo != NULL) { VERBOSE(1,"BEST TRANSLATION: " << *hypo << endl); VERBOSE(3,"Best path: "); Backtrack(hypo); VERBOSE(3,"0" << std::endl); if (!m_surpressSingleBestOutput) { if (StaticData::Instance().GetOutputHypoScore()) { cout << hypo->GetTotalScore() << " "; } if (StaticData::Instance().IsPathRecoveryEnabled()) { OutputInput(cout, hypo); cout << "||| "; } OutputBestSurface(cout, hypo, m_outputFactorOrder, reportSegmentation, reportAllFactors); cout << endl; } } else { VERBOSE(1, "NO BEST TRANSLATION" << endl); if (!m_surpressSingleBestOutput) { cout << endl; } } }
void GraphMatcher::GenerateMatchings() { vector<int> matching; matching.reserve(A->nodes.size()); used.clear(); matchingScore.clear(); bestMatchings.clear(); Backtrack(0, matching); }
void IOWrapper::Backtrack(const Hypothesis *hypo) { if (hypo->GetPrevHypo() != NULL) { VERBOSE(3,hypo->GetId() << " <= "); Backtrack(hypo->GetPrevHypo()); } }
void Backtrack(int i) { if(i>n) { bestp=cp; return; } if(cw+w[i]<=c) //left tree { cw+=w[i]; cp+=p[i]; Backtrack(i+1); cw-=w[i]; cp-=p[i]; if(Bound(i+1)>bestp) Backtrack(i+1); } }
static void ProcessItem() { s_bFailed = false; s_index = 0; int a[5] = {0}; Backtrack(a, 0, 5); if (!s_bFailed) printf("tautology\n"); else printf("not\n"); }
void IOWrapper::Backtrack(const ChartHypothesis *hypo) { const vector<const ChartHypothesis*> &prevHypos = hypo->GetPrevHypos(); vector<const ChartHypothesis*>::const_iterator iter; for (iter = prevHypos.begin(); iter != prevHypos.end(); ++iter) { const ChartHypothesis *prevHypo = *iter; VERBOSE(3,prevHypo->GetId() << " <= "); Backtrack(prevHypo); } }
void GraphMatcher::Backtrack(int num, vector<int>& matching) { if (matching.size() == A->nodes.size()) { FinishMatching(matching); } else { for (int numb = 0; numb <= B->nodes.size(); numb++) { int i = numb - 1; if (CanMatch(num, i, matching)) { matching.push_back(i); used.push_back(i); if (i == -1) ignore--; Backtrack(num + 1, matching); if (i == -1) ignore++; used.pop_back(); matching.pop_back(); } } } }
void IOWrapper::OutputBestHypo(const ChartHypothesis *hypo, long translationId) { if (!m_singleBestOutputCollector) return; std::ostringstream out; IOWrapper::FixPrecision(out); if (hypo != NULL) { VERBOSE(1,"BEST TRANSLATION: " << *hypo << endl); VERBOSE(3,"Best path: "); Backtrack(hypo); VERBOSE(3,"0" << std::endl); if (StaticData::Instance().GetOutputHypoScore()) { out << hypo->GetTotalScore() << " "; } if (StaticData::Instance().IsPathRecoveryEnabled()) { out << "||| "; } Phrase outPhrase(ARRAY_SIZE_INCR); hypo->CreateOutputPhrase(outPhrase); // delete 1st & last CHECK(outPhrase.GetSize() >= 2); outPhrase.RemoveWord(0); outPhrase.RemoveWord(outPhrase.GetSize() - 1); const std::vector<FactorType> outputFactorOrder = StaticData::Instance().GetOutputFactorOrder(); string output = outPhrase.GetStringRep(outputFactorOrder); out << output << endl; } else { VERBOSE(1, "NO BEST TRANSLATION" << endl); if (StaticData::Instance().GetOutputHypoScore()) { out << "0 "; } out << endl; } m_singleBestOutputCollector->Write(translationId, out.str()); }
int main() { int i; bestp=0; printf("请输入背包最大容量:\n"); scanf("%d",&c); printf("请输入物品个数:\n"); scanf("%d",&n); printf("请依次输入物品的重量:\n"); for(i=1;i<=n;i++) scanf("%d",&w[i]); printf("请依次输入物品的价值:\n"); for(i=1;i<=n;i++) scanf("%d",&p[i]); Sort(); Backtrack(1); printf("最大价值为:\n"); printf("%d\n",bestp); printf("被选中的物品依次是(0表示未选中,1表示选中)\n"); return 0; }
static void Backtrack(int* a, int k, int n) { if (s_bFailed) return; if (k == n) { if (!IsTautology(a, n)) { s_bFailed = true; return; } } else { int c[2] = {0, 1}; for (int i = 0; i<2; i++) { a[k] = c[i]; Backtrack(a, k+1, n); } } }
/** The brute force backtrack algorithm. * @return 1 if the grid was solved or 0 if not. */ static int Backtrack(void) { int Row, Column; unsigned int Bitmask_Missing_Numbers, Tested_Number; // Find the first empty cell (don't remove the stack top now as the backtrack can return soon if no available number is found) if (CellsStackReadTop(&Row, &Column) == 0) { // No empty cell remain and there is no error in the grid : the solution has been found if (GridIsCorrectlyFilled()) return 1; // A bad grid was generated... #ifdef DEBUG printf("[Backtrack] Bad grid generated !\n"); #endif return 0; } // Get available numbers for this cell Bitmask_Missing_Numbers = GridGetCellMissingNumbers(Row, Column); // If no number is available a bad grid has been generated... It's safe to return here as the top of the stack has not been altered if (Bitmask_Missing_Numbers == 0) return 0; #ifdef DEBUG printf("[Backtrack] Available numbers for (row %d ; column %d) : ", Row, Column); GridShowBitmask(Bitmask_Missing_Numbers); #endif // Try each available number for (Tested_Number = 0; Tested_Number < Grid_Size; Tested_Number++) { // Loop until an available number is found if (!(Bitmask_Missing_Numbers & (1 << Tested_Number))) { Avoided_Bad_Solutions_Count++; continue; } // Try the number GridSetCellValue(Row, Column, Tested_Number); GridRemoveCellMissingNumber(Row, Column, Tested_Number); CellsStackRemoveTop(); // Really try to fill this cell, removing it for next simulation step Loops_Count++; #ifdef DEBUG printf("[Backtrack] Modified grid :\n"); GridShowDifferences(GRID_COLOR_CODE_BLUE); putchar('\n'); #endif // Simulate next state if (Backtrack() == 1) return 1; // Good solution found, go to tree root // Bad solution found, restore old value GridSetCellValue(Row, Column, GRID_EMPTY_CELL_VALUE); GridRestoreCellMissingNumber(Row, Column, Tested_Number); CellsStackPush(Row, Column); // The cell is available again Bad_Solutions_Found_Count++; #ifdef DEBUG printf("[Backtrack] Restored grid :\n"); GridShowDifferences(GRID_COLOR_CODE_RED); putchar('\n'); #endif } // All numbers were tested unsuccessfully, go back into the tree return 0; }
//------------------------------------------------------------------------------------------------- // Entry point //------------------------------------------------------------------------------------------------- int main(int argc, char *argv[]) { char *String_Grid_File_Name; int Starting_Number; // Show the title printf("+---------------+\n"); printf("| Sudoku Solver |\n"); printf("+---------------+\n\n"); // Check parameters if (argc != 3) { printf("Error : bad parameters.\n"); printf("Usage : %s DisplayedGridStartingNumber SudokuGridFileName\n", argv[0]); printf("The value DisplayedGridStartingNumber is added to all the numbers when the grid is displayed.\n"); return EXIT_FAILURE; } Starting_Number = atoi(argv[1]); String_Grid_File_Name = argv[2]; GridSetDisplayStartingNumber(Starting_Number); // Try to load the grid file switch (GridLoadFromFile(String_Grid_File_Name)) { case -1: printf("Error : can't open file %s.\n", String_Grid_File_Name); return EXIT_FAILURE; case -2: printf("Error : grid size or data is bad.\nThe maximum allowed size is %d.\n", CONFIGURATION_GRID_MAXIMUM_SIZE); return EXIT_FAILURE; case -3: printf("Error : bad grid file. There are not enough numbers to fill the grid.\n"); return EXIT_FAILURE; } Grid_Size = GridGetSize(); // Show file name printf("File : %s.\n\n", String_Grid_File_Name); // Show grid printf("Grid to solve :\n"); GridShow(); putchar('\n'); // Start solving if (Backtrack() == 1) { printf("Grid successfully solved in %llu loops.\n", Loops_Count); printf("Bad solutions found before the good one : %llu\n", Bad_Solutions_Found_Count); printf("Avoided bad solutions : %llu\n", Avoided_Bad_Solutions_Count); printf("\nSolved grid :\n"); GridShow(); putchar('\n'); return EXIT_SUCCESS; } // Backtracking lead to the original grid, it is not solvable printf("Failure : none stategie can solve this grid, sorry.\n\n"); printf("Found grid :\n"); GridShow(); putchar('\n'); return EXIT_FAILURE; }