Exemple #1
0
int main(int argc, char *argv[])
{
	QString ampFile("../example_data/amplitude_199x199_double.raw");
	QString phaFile("../example_data/phase_199x199_double.raw");
	QString solFile("../example_data/solution_199x199_double.raw");

	QSize rawSize(199,199);
	int sz = rawSize.width() * rawSize.height();

	QFile amplitude(ampFile);
	if (!amplitude.open(QIODevice::ReadOnly))
	{
		qDebug() << "amplitude file not found" << ampFile;
		return -1;
	}

	double* amp = new double[sz];
	amplitude.read((char*)amp, sz * sizeof(amp[0]));	
	amplitude.close();


	QFile phase(phaFile);
	if (!phase.open(QIODevice::ReadOnly))
	{
		qDebug() << "phase file not found" << phaFile;
		return -1;
	}

	double* pha = new double[sz];
	phase.read((char*)pha, sz * sizeof(pha[0]));
	phase.close();

	GSATracking up;
	up.SetBranchCutMode(GSATracking::AMPLITUDETRACING); // aplitude tracking mode
	up.SetCutsDilate(7); // dilatation kernel radius
	up.SetInterpolate(true); // interpolation enabled
	up.SetWeightedInterpolation(true); // amplitude based weighted interpolation

	double* sol = up.UnWrapp(pha, amp, rawSize);


	QFile solution(solFile);
	solution.open(QIODevice::WriteOnly);
	solution.write((char*)sol, sz * sizeof(sol[0]));
	solution.close();


	delete amp;
	delete pha;

	qDebug() << "positive residues:" << up.PositiveResidueCount();
	qDebug() << "negative residues:" << up.NegativeResidueCount();
	qDebug() << "solution file created:" << solFile;

	qDebug() << endl << "press any key";
	std::cin.get();
	return 0;
}
Report ElasticProblem2DOnCellV2<dim>::calculate_cells_stress ()
{
    cells_stress .clear ();

    dealii::QGauss<dim> quadrature_formula(2);

    dealii::FEValues<dim> fe_values (finite_element, quadrature_formula,
            dealii::update_gradients | 
            dealii::update_quadrature_points | dealii::update_JxW_values);

    const uint8_t dofs_per_cell = finite_element.dofs_per_cell;
    const uint8_t num_quad_points = quadrature_formula.size();

    typename dealii::DoFHandler<dim>::active_cell_iterator cell =
        this->domain.dof_handler.begin_active();

    typename dealii::DoFHandler<dim>::active_cell_iterator endc =
        this->domain.dof_handler.end();

    std::vector<unsigned int> local_dof_indices (dofs_per_cell);

    size_t cell_num = 0;
    for (; cell != endc; ++cell)
    {
            fe_values .reinit (cell);

            dbl area = 0.0;
            for(st i = 0; i < num_quad_points; ++i)
                area += fe_values.JxW(o);

            dbl mat_id = cell->material_id();

                
                std::array<dbl,2> deform;
                    for (auto i : {x, y}) 
                    {
                        deform[i][j] = 0.0;

                        for(auto i : {1, 2, 3, 4})
                        {
                    
                            dbl summ = 0.0;
                            for (size_t q_point = 0; q_point < num_quad_points; ++q_point)
                                summ += 
                                    fe_values.shape_grad (n, q_point)[i] *
                                    fe_values.JxW(q_point);
                            deform[i] += 
                                solution(cell->vertex_dof_index(n, 0)) * 
                                summ;
                        };
                        deform[i] /= area;
                    
                    };
    };
    REPORT_USE( 
            Report report;
            report.result = true;
            _return (report););
//Solves the puzzle
void puzzle::solve(){
    
    std::cout << "Finding edge costs..." << std::endl;
    fill_costs();
    std::vector<match_score>::iterator i= matches.begin();
    PuzzleDisjointSet p((int)pieces.size());
    
  
//You can save the individual pieces with their id numbers in the file name
//If the following loop is uncommented.
//    for(int i=0; i<pieces.size(); i++){
//        std::stringstream filename;
//        filename << "/tmp/final/p" << i << ".png";
//        cv::imwrite(filename.str(), pieces[i].full_color);
//    }
    
    int output_id=0;
    while(!p.in_one_set() && i!=matches.end() ){
        int p1 = i->edge1/4;
        int e1 = i->edge1%4;
        int p2 = i->edge2/4;
        int e2 = i->edge2%4;
        
//Uncomment the following lines to spit out pictures of the matched edges...
//        cv::Mat m = cv::Mat::zeros(500,500,CV_8UC1);
//        std::stringstream out_file_name;
//        out_file_name << "/tmp/final/match" << output_id++ << "_" << p1<< "_" << e1 << "_" <<p2 << "_" <<e2 << ".png";
//        std::vector<std::vector<cv::Point> > contours;
//        contours.push_back(pieces[p1].edges[e1].get_translated_contour(200, 0));
//        contours.push_back(pieces[p2].edges[e2].get_translated_contour_reverse(200, 0));
//        cv::drawContours(m, contours, -1, cv::Scalar(255));
//        std::cout << out_file_name.str() << std::endl;
//        cv::imwrite(out_file_name.str(), m);
//        std::cout << "Attempting to merge: " << p1 << " with: " << p2 << " using edges:" << e1 << ", " << e2 << " c:" << i->score << " count: "  << output_id++ <<std::endl;
        p.join_sets(p1, p2, e1, e2);
        i++;
    }
    
    if(p.in_one_set()){
        std::cout << "Possible solution found" << std::endl;
        solved = true;
        solution = p.get(p.find(1)).locations;
        solution_rotations = p.get(p.find(1)).rotations;
        
        for(int i =0; i<solution.size[0]; i++){
            for(int j=0; j<solution.size[1]; j++){
                int piece_number = solution(i,j);
                pieces[piece_number].rotate(4-solution_rotations(i,j));
            }
        }
        
        
    }
    
    
    
}
Exemple #4
0
void main()
{
	long int a;
	int X,Y,D;

	scanf("%d %d %d",&X,&Y,&D);
	a=solution(X,Y,D);
	printf("Ans: %li\n \r",a);
}
Exemple #5
0
int main(void)
{
  int16_t *array = malloc(5 * sizeof(int16_t));
  for(size_t i = 0; i < 5; i++) array[i] = i;

  array = solution(array, 5, 5);

  for(size_t i = 0; i < 5; i++) printf("%d ", array[i]);
}
int main(int argc, const char * argv[])
{
    int A[] = {9,3,9,3,9,7,9};
    int N = 7;
    
    printf("%d\n", solution(A,N));
    
    return 0;
}
int main() {
    int M, n;
    scanf("%d", &M);
    while (M--) {
        scanf("%d", &n);
        printf("%d\n", solution(n));
    }
    //system("pause");
    return 0;
}
Exemple #8
0
TEST(matrix3, GetTranslationMatrix)
{
	Vector2 v1(3, -7);
	Matrix3 m = m.GetTranslationMatrix(v1);
	Matrix3 solution(
		1, 0, 3,
		0, 1, -7,
		0, 0, 1);
	EXPECT_TRUE(m == solution);
}
void
AuxiliarySystem::computeNodalVars(ExecFlagType type)
{
  std::vector<AuxWarehouse> & auxs = _auxs(type);

  // Do we have some kernels to evaluate?
  bool have_block_kernels = false;
  for (std::set<SubdomainID>::const_iterator subdomain_it = _mesh.meshSubdomains().begin();
      subdomain_it != _mesh.meshSubdomains().end();
      ++subdomain_it)
  {
    have_block_kernels |= (auxs[0].activeBlockNodalKernels(*subdomain_it).size() > 0);
  }

  Moose::perf_log.push("update_aux_vars_nodal()","Solve");
  PARALLEL_TRY {
    if (have_block_kernels)
    {
      ConstNodeRange & range = *_mesh.getLocalNodeRange();
      ComputeNodalAuxVarsThread navt(_mproblem, *this, auxs);
      Threads::parallel_reduce(range, navt);

      solution().close();
      _sys.update();
    }
  }
  PARALLEL_CATCH;
  Moose::perf_log.pop("update_aux_vars_nodal()","Solve");

  //Boundary AuxKernels
  Moose::perf_log.push("update_aux_vars_nodal_bcs()","Solve");
  PARALLEL_TRY {
    // after converting this into NodeRange, we can run it in parallel
    ConstBndNodeRange & bnd_nodes = *_mesh.getBoundaryNodeRange();
    ComputeNodalAuxBcsThread nabt(_mproblem, *this, auxs);
    Threads::parallel_reduce(bnd_nodes, nabt);

    solution().close();
    _sys.update();
  }
  PARALLEL_CATCH;
  Moose::perf_log.pop("update_aux_vars_nodal_bcs()","Solve");
}
Exemple #10
0
int
addConfig(Config config, struct puzzle *back)
{
  unsigned hashvalue;
  struct puzzle *newpiece;
  struct puzzlelist *newlistentry;

  hashvalue = hash(config);

  newpiece = hashtable[hashvalue % HASHSIZE];
  while (newpiece != NULL) {
    if (newpiece->hashvalue == hashvalue) {
      int i, j;

      for (i = 0; i < WIDTH; i++) {
        for (j = 0; j < HEIGHT; j++) {
          if (convert[(int)config[j][i]] !=
            convert[(int)newpiece->pieces[j][i]])
            goto nomatch;
        }
      }
      return 0;
    }
  nomatch:
    newpiece = newpiece->next;
  }

  newpiece = (struct puzzle *) malloc(sizeof(struct puzzle));
  newpiece->next = hashtable[hashvalue % HASHSIZE];
  newpiece->hashvalue = hashvalue;
  memcpy(newpiece->pieces, config, HEIGHT * WIDTH);
  newpiece->backptr = back;
  newpiece->solnptr = NULL;
  hashtable[hashvalue % HASHSIZE] = newpiece;

  newlistentry = (struct puzzlelist *) malloc(sizeof(struct puzzlelist));
  newlistentry->puzzle = newpiece;
  newlistentry->next = NULL;

  if (lastentry) {
    lastentry->next = newlistentry;
  } else {
    puzzles = newlistentry;
  }
  lastentry = newlistentry;

  if (back == NULL) {
    startPuzzle = newpiece;
  }
  if (solution(config)) {
    solidifyChain(newpiece);
    return 1;
  }
  return 0;
}
Exemple #11
0
int main() {

    printf("Answer: %lu\n", solution());

    timestamp_t t0 = get_timestamp();

    for (int i = 0; i < 3; ++i) {
        solution();
    }

    timestamp_t t1 = get_timestamp();

    double t_elapsed = (t1 - t0) / 1000000.0L / 3;

    if (t_elapsed < 3) {
         int run_time = 10;
         unsigned long long n_iters = run_time / t_elapsed;

         timestamp_t t0 = get_timestamp();

         for (int i = 0; i < n_iters; ++i) {
             solution();
         }

         timestamp_t t1 = get_timestamp();
         t_elapsed = (t1 - t0) / 1000000.0L / n_iters;
    }

    double exp_t = log10(t_elapsed);

    if (exp_t > 0) {
        printf("Average Duration: %.3g s\n", t_elapsed);
    } else if (exp_t > -3) {
        printf("Average Duration: %.3Lg ms\n", t_elapsed * 1000.0L);
    } else if (exp_t > -6) {
        printf("Average Duration: %.3Lg µs\n", t_elapsed * 1000000.0L);
    } else {
        printf("Average Duration: %.3Lg ns\n", t_elapsed * 1000000000.0L);
    }

    return 0;
}
void run(const casema::ModelData<mpfr::mpreal>& model, ProgramOptions<mpfr::mpreal>& opts)
{
    // Log10(errorPrefactor)
    const mpfr::mpreal errorPrefactor = log10(sqrt(mpfr::mpreal(2))) + model.colLength * model.velocity / (2 * model.colDispersion * log(mpfr::mpreal(10)));
    const mpfr::mpreal T = opts.tMax / mpfr::mpreal(2) * mpfr::mpreal("1.01");
    const mpfr::mpreal errorExponentFactor = model.colLength * sqrt(casema::Constants<mpfr::mpreal>::pi() / (2 * T * model.colDispersion)) / log(mpfr::mpreal(10));

    std::vector<mpfr::mpcomplex> output(opts.summands);
    std::vector<mpfr::mpreal> error(opts.summands, errorPrefactor);
    Inlet_t inlet(model);

    if (model.kineticBinding)
    {
        typedef casema::laplaceSolution::SingleComponentLinearDynamic<mpfr::mpreal, mpfr::mpreal, Inlet_t> Solution_t;
	    Solution_t solution(model, inlet);
        if (opts.withoutInlet)
            fourierCoeff<Solution_t, mpfr::mpreal, mpfr::mpcomplex>(opts.precision, opts.summands, opts.tMax, opts.sigma, solution, errorExponentFactor, output, error);
        else
            fourierCoeff<Solution_t, mpfr::mpreal, mpfr::mpcomplex>(opts.precision, opts.summands, opts.tMax, opts.sigma, solution, inlet, errorExponentFactor, output, error);
    }
    else
    {
        typedef casema::laplaceSolution::SingleComponentLinearRapidEquilibrium<mpfr::mpreal, mpfr::mpreal, Inlet_t> Solution_t;
	    Solution_t solution(model, inlet);
        if (opts.withoutInlet)
            fourierCoeff<Solution_t, mpfr::mpreal, mpfr::mpcomplex>(opts.precision, opts.summands, opts.tMax, opts.sigma, solution, errorExponentFactor, output, error);
        else
            fourierCoeff<Solution_t, mpfr::mpreal, mpfr::mpcomplex>(opts.precision, opts.summands, opts.tMax, opts.sigma, solution, inlet, errorExponentFactor, output, error);
    }

    if (opts.outFile.empty())
    {
        writeMeta(std::cout, model.kineticBinding, opts);
        writeResult(std::cout, output, error, opts.outPrecision, opts.skipSummands);
    }
    else
    {
        std::ofstream fs(opts.outFile, std::ofstream::out | std::ofstream::trunc);
        writeMeta(fs, model.kineticBinding, opts);
        writeResult(fs, output, error, opts.outPrecision, opts.skipSummands);
    }
}
Exemple #13
0
int main()
{
  int n,k;
  while(1)
  {
    scanf("%d %d",&n,&k);
    if(!n && !k) break;
    printf("%d\n",solution(n,k));
  }
  return 0;
}
int main() {
    int N, T;
    int value[50];
    scanf("%d%d", &N, &T);
    while (N || T) {
        for (int i = 0; i < N; ++i) scanf("%d", value + i);
        printf("%d\n", solution(N, T, value));
        scanf("%d%d", &N, &T);
    }
    return 0;
}
Exemple #15
0
      MeshFunctionSharedPtr<Scalar> Limiter<Scalar>::get_solution()
      {
        // A check.
        warn_if(this->component_count > 1, "One solution asked from a Limiter, but multiple solutions exist for limiting.");

        MeshFunctionSharedPtr<Scalar> solution(new Solution<Scalar>());
        Hermes::vector<MeshFunctionSharedPtr<Scalar> > solutions;
        solutions.push_back(solution);
        this->get_solutions(solutions);
        return solutions.back();
      }
Exemple #16
0
main()
{
        struct node triangle;
               
        printf("Euler Problem 18\n"); 
        
        test_sweep(0);

        printf("Running...\n");      
        printf("solution() = %i\n", solution(&triangle));
}
void
AuxiliarySystem::computeElementalVars(ExecFlagType type)
{
  Moose::perf_log.push("update_aux_vars_elemental()","Solve");

  std::vector<AuxWarehouse> & auxs = _auxs(type);
  bool need_materials = true; //type != EXEC_INITIAL;

  PARALLEL_TRY {
    bool element_auxs_to_compute = false;

    for (unsigned int i=0; i<auxs.size(); i++)
      element_auxs_to_compute |= auxs[i].allElementKernels().size();

    if (element_auxs_to_compute)
    {
      ConstElemRange & range = *_mesh.getActiveLocalElementRange();
      ComputeElemAuxVarsThread eavt(_mproblem, *this, auxs, need_materials);
      Threads::parallel_reduce(range, eavt);

      solution().close();
      _sys.update();
    }

    bool bnd_auxs_to_compute = false;
    for (unsigned int i=0; i<auxs.size(); i++)
      bnd_auxs_to_compute |= auxs[i].allElementalBCs().size();
    if (bnd_auxs_to_compute)
    {
      ConstBndElemRange & bnd_elems = *_mesh.getBoundaryElementRange();
      ComputeElemAuxBcsThread eabt(_mproblem, *this, auxs, need_materials);
      Threads::parallel_reduce(bnd_elems, eabt);

      solution().close();
      _sys.update();
    }

  }
  PARALLEL_CATCH;
  Moose::perf_log.pop("update_aux_vars_elemental()","Solve");
}
Exemple #18
0
int main(){

    std::vector<int> v;
    v.push_back(2);
    v.push_back(3);
    v.push_back(1);
    v.push_back(5);

    std::cout << solution(v);

    return 0;
}
void QtFactor::setValues(QString QS_p, QString QS_s) {
    long int p, s;
    bool b_toInt;
    p = QS_p.toInt(&b_toInt, 10);
    s = QS_s.toInt(&b_toInt, 10);
    cout << "Integer values: " << p << " " << s << endl;

    if((productCache == p) && (sumCache == s))
        emit(solution(QStringulize(solutionCache)));

    facc->setValues(p, s);

    try {
            facc->compute();
            solutionCache = facc->getSolution();
            emit(solution(QStringulize(solutionCache)));
    }
    catch(exception &e) {
            emit(solution(QString(e.what())));
    }
}
Exemple #20
0
std::vector<float> SegmentationImpl::computeMetrics() const
{
    if (!solutionAvailable()) {
        LERROR << "Solution not available to compute metrics";
        return std::vector<float>();
    }
    if (!inputImageGroundTruthAvailable()) {
        LERROR << "No ground truth available to compute metrics";
        return std::vector<float>();
    }
    return computeMetrics(solution(), inputImageGroundTruth(), settings()->numLabels());
}
Exemple #21
0
TEST(StackMachineTest, DISABLED_LengthTest) {
    // Tests solution with a 128*1024*1024 char long input string (128 MB).
    // Since this requies _at least_ a 16-bit integer for each number, this
    // test allocates at least a total of 384 MB of memory. On 32-bit systems,
    // this will likely end up allocating around 640 MB of memory, and on
    // 64-bit systems, around 1152 MB.
    constexpr auto length = std::size_t{128*1024*1024};
    auto longInput = std::string(length, '1');
    ASSERT_EQ(length, longInput.size());

    EXPECT_EQ(1, solution(longInput))
        << "NumberTest failed with input of size = " << longInput.size();

    longInput.append("+");
    EXPECT_EQ(2, solution(longInput))
        << "AdditionTest failed with input of size = " << longInput.size();

    longInput.append("2*");
    EXPECT_EQ(4, solution(longInput))
        << "MultiplicationTest failed with input of size = " << longInput.size();
}
Exemple #22
0
void
AuxiliarySystem::computeNodalVars(ExecFlagType type)
{
  Moose::perf_log.push("update_aux_vars_nodal()", "Execution");

  // Reference to the Nodal AuxKernel storage
  const MooseObjectWarehouse<AuxKernel> & nodal = _nodal_aux_storage[type];

  // Block Nodal AuxKernels
  PARALLEL_TRY {
    if (nodal.hasActiveBlockObjects())
    {
      ConstNodeRange & range = *_mesh.getLocalNodeRange();
      ComputeNodalAuxVarsThread navt(_fe_problem, nodal);
      Threads::parallel_reduce(range, navt);

      solution().close();
      _sys.update();
    }
  }
  PARALLEL_CATCH;
  Moose::perf_log.pop("update_aux_vars_nodal()", "Execution");

  // Boundary Nodal AuxKernels
  Moose::perf_log.push("update_aux_vars_nodal_bcs()", "Execution");
  PARALLEL_TRY {
    if (nodal.hasActiveBoundaryObjects())
    {
      ConstBndNodeRange & bnd_nodes = *_mesh.getBoundaryNodeRange();
      ComputeNodalAuxBcsThread nabt(_fe_problem, nodal);
      Threads::parallel_reduce(bnd_nodes, nabt);

      solution().close();
      _sys.update();
    }
  }
  PARALLEL_CATCH;

  Moose::perf_log.pop("update_aux_vars_nodal_bcs()", "Execution");
}
Exemple #23
0
/*
 * maximize c^T x subject to Ax = b and x >= 0
 *
 * inplace, b is last column of A, c first row
 */
static void simplex2(unsigned int D, unsigned int N, float A[D + 1][N + 1])
{
	// 2. Loop over all columns

//	print_tableaux(D, N, A);

	while (true) {

		unsigned int i = 0;

		for (i = 0; i < N; i++)
			 if (A[0][i] < 0.)
				break;

		if (i == N)
			break;

		// 3. find pivot element

		// Bland's rule

		int pivot_index = -1;
		float pivot_value = 0.;

		for (unsigned int j = 1; j < D + 1; j++) {

			if (0. < A[j][i]) {

				float nval = A[j][N] / A[j][i];

				if ((-1 == pivot_index) || (nval < pivot_value)) {

					pivot_value = nval;
					pivot_index = j;
				}
			}
		}

		if (-1 == pivot_index)
			break;

//		printf("PI %dx%d\n", pivot_index, i);

		trafo(D + 1, N + 1, A, pivot_index, i);

//		print_tableaux(D, N, A);
		float x[N];
		solution(D, N, x, A);
		assert(feasible_p(D, N, x, A));
	}
//	print_tableaux(D, N, A);
}
Exemple #24
0
bool GodotSharpEditor::_create_project_solution() {

	EditorProgress pr("create_csharp_solution", "Generating solution...", 2);

	pr.step("Generating C# project...");

	String path = OS::get_singleton()->get_resource_dir();
	String name = ProjectSettings::get_singleton()->get("application/config/name");
	if (name.empty()) {
		name = "UnnamedProject";
	}

	String guid = CSharpProject::generate_game_project(path, name);

	if (guid.length()) {

		NETSolution solution(name);

		if (!solution.set_path(path)) {
			show_error_dialog("Failed to create solution.");
			return false;
		}

		Vector<String> extra_configs;
		extra_configs.push_back("Tools");

		solution.add_new_project(name, guid, extra_configs);

		Error sln_error = solution.save();

		if (sln_error != OK) {
			show_error_dialog("Failed to save solution.");
			return false;
		}

		if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_CORE))
			return false;

		if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_EDITOR))
			return false;

		pr.step("Done");

		// Here, after all calls to progress_task_step
		call_deferred("_remove_create_sln_menu_option");

	} else {
		show_error_dialog("Failed to create C# project.");
	}

	return true;
}
void CVRP::constructGreedyRandomizedSolution(){
	int n = 0;
	double waitTime = 0.0;
	int nVehi = deduce_nVehicles(0);
	vector<Route*> solution(nVehi, new Route);
	vector<int> route_capacity(nVehi, 0);
	vector<double> routes_times(nVehi, 0.0);
	vector<vector<Costumer*> > sol_candidates(solution.size(), vector<Costumer*> ());
	
	dep.nVehicles = nVehi;
		
	for(int i = 0; i < solution.size(); i++){
		solution[i] = new Route;
	}
	//Initialize the solution with nearby close clients
	init_solution(solution, routes_times, route_capacity, n);

	while(n != clients.size()){
		//Update the list of candidates
		sol_candidates = update_list(solution, routes_times, n);
	
		for(int c = 0; c < sol_candidates.size(); c++){
			sort(sol_candidates[c].begin(), sol_candidates[c].end(), saving_heuristic);
		}
		//shrink_routes(solution);
		select_candidate(solution, sol_candidates, routes_times, route_capacity, n);
	}
	double sum = 0.0;	
	cout << "Solution size: " << solution.size() << endl;
	for(Route *r : solution){
		for(Costumer *c : r->clients){
			sum += c->cost;
			cout << c->id << " ";
		}
		cout << endl;
	}
	cout << sum << endl;
	
	cout << endl;
	/*for(int i = 0; i < solution.size(); i++){
		solution[i]->clients.push_front(new Costumer(0, dep.coord,0,0,0,0));
		solution[i]->clients.push_back(new Costumer(0, dep.coord,0,0,0,0));
	}*/
	sol = solution;
	for(Route *r : solution){
		for(int i = 0; i < r->clients.size()-1; i++){
			cout << r->clients[i]->id << ":" << r->clients[i]->arrTime + r->clients[i]->servTime << " " << r->clients[i+1]->id << ":" << r->clients[i+1]->dTime << endl;  
		}
		cout << endl;
	}
	save();
}
Exemple #26
0
const std::string ompl::geometric::SimpleSetup::getSolutionPlannerName() const
{
    if (pdef_)
    {
        const ompl::base::PathPtr path;              // convert to a generic path ptr
        ompl::base::PlannerSolution solution(path);  // a dummy solution

        // Get our desired solution
        pdef_->getSolution(solution);
        return solution.plannerName_;
    }
    throw Exception("No problem definition found");
}
Exemple #27
0
int main(){

	std::vector<int> A;
	A.push_back(4);
	A.push_back(1);
	A.push_back(3);
	A.push_back(2);
;

	int s=solution(A);
	std::cout<< "Answer: "<<s<<std::endl;
	return 0;
}
// 전역변수로 상태공간을 관리하기 번거로우므로 함수의 인자로 현재 광고를 보는 친구를 넘겨 준다
// 그렇게 된다면 다시 원래되로 돌려주는 코드가 없어지게 되므로 신경쓸게 하나 줄어든다
// 이 때 state는 bit mask를 이용해 손쉽게 관리해 줄 수 있다
// 구현 편의상 사람 번호가 1~N 번이 아니라 0~N-1 번으로 바꾸어 준다
void solution(int pos, int state, int cnt)
{
	// 상태공간트리의 리프노드에 도달했을때
	if(pos==N)
	{
		// 모든 사람들이 광고를 볼 수있다면 선택한 사람의 수화 sol값 중 최소값을 선택
		if(state==(1<<N)-1) sol=min(sol, cnt);
		return;
	}

	// 현재 위치의 사람을 선택하지 않은 경우
	solution(pos+1, state, cnt);
	
	// 현재 위치의 사람을 선택한 경우
	// 현재 위치의 사람과 친구라면 해당 bit를 on시켜준다
	// 그 뒤 재귀호출을 실행.
	for(int i=0 ; i<N ; i++)
		if(isFriend[pos][i]) state|=(1<<i);
	solution(pos+1, state, cnt+1);

	// call by value로 넘기기 때문에 다시 되돌려 줄 필요가 없다
}
int main()
{
    int p[]={0,1,5,8,9,10,17,17,20,24,30};
    int r[MAX];
    initRod(p,SIZE(p)-1,r);    
    
    for(int i=0;i<SIZE(p);i++)
    {
            printf("%d=%d\t",i,r[i]);
            solution(p,r,i);
    }
    getchar();
}
 vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
     queue<string> Q;
     unordered_map<string, bool> visited;
     unordered_map<string, int> level;
     unordered_map<string, unordered_set<string>> parents;
     Q.push(beginWord);
     level[beginWord] = 1;
     parents[beginWord].insert(beginWord);
     int depth = INT_MAX;
     while(!Q.empty()) {
         string node = Q.front();
         visited[node] = true;
         Q.pop();
         if(level[node] > depth) {
             break;
         }
         if(level[node] == depth and node != endWord) {
             continue;    
         }
         if(isNextState(node, endWord)) {
             level[endWord] = level[node] + 1;
             parents[endWord].insert(node);
             Q.push(endWord);
             depth = level[endWord];
             continue;
         }
         vector<string> neighs;
         findAdjList(node, wordList, neighs);
         for(int i = 0; i < (int)neighs.size(); ++i) {
             string neigh = neighs[i];
             if(level[neigh] > 0) {
                 if(level[node] >= level[neigh]) {
                     continue;
                 }
             }
             if(!visited[neigh]) {
                 Q.push(neigh);
                 parents[neigh].insert(node);
                 level[neigh] = level[node] + 1;
                 if(neigh == endWord) {
                     depth = level[neigh];
                 }
             }
         }
     }
     vector<vector<string>> result;
     if(depth == INT_MAX) return result;
     vector<string> solution(depth, "");
     findShortestPaths(endWord, depth - 1, parents, solution, result);
     return result;
 }