Ejemplo n.º 1
0
 vector<vector<int>> subsetsWithDup(vector<int>& nums) {
     vector<vector<int>> res{};
     vector<int> trace{};
     sort(nums.begin(), nums.end());
     backTracking(nums, trace, 0, res);
     return res;
 }
Ejemplo n.º 2
0
 vector<vector<string> > solveNQueens(int n) {
     vector<vector<string> > answers;
     C = new int[n];
     backTracking(answers,0,n);
     delete []C;
     return answers;
 }
Ejemplo n.º 3
0
 void backTracking(vector<vector<string> >& answers,int cur,int n){
     if(cur==n){
         string str;
         for(int k=0;k<n;k++)
             str += ".";
         vector<string> ans;
         for(int l=0;l<n;l++){
             str[C[l]]='Q';
             ans.push_back(str);
             str[C[l]]='.';
         }
         answers.push_back(ans);
     }
     else{
         for(int i=0;i<n;i++){
             bool ok=true;
             C[cur]=i;
             for(int j=0;j<cur;j++){
                 if(C[j]==i||C[j]-j==i-cur||C[j]+j==i+cur){
                     ok=false;
                     break;
                 }
             }
             if(ok)
                 backTracking(answers,cur+1,n);
         }
     }
 }
Ejemplo n.º 4
0
int solver(int *map, int x1, int y1, int x2, int y2, int *original_stones, int n)
{
	//dump(map, x1, y1, x2, y2, original_stones, n);

	// Prepare
	int i, j, k;
	stoneEncode(global_stones, original_stones, n);
	global_original_stones = original_stones;
	global_n = n;

	global_x1 = x1;
	global_y1 = y1;
	global_x2 = x2;
	global_y2 = y2;

	for (i=0; i<1024; i++) map[i] = (map[i] == 0) ? -1 : -2;

	// Search
	global_best.score = 1024;
	bestScore(&global_best, map);

	for (i=0; i<n; i++) {
		int8_t op[256];
		BlockDefineOperation(global_stones[i].list, op);

		int *base = &global_operation[i << 8];
		*base = 0;

		for (j=0; j<8; j++) {
			int8_t *pp = &op[j << 5];
			if (pp[0] == INT8_MAX) continue;
			int *p = &base[(*base) << 5];

			for (k=1; k<global_stones[i].len; k++) {
				p[k << 1] = pp[k << 1];
				p[(k << 1) + 1] = pp[(k << 1) + 1];
			}

			(*base)++;
		}
	}

	global_sumlen[n] = 0;
	for (i=(n-1); i>=0; i--) global_sumlen[i] = global_sumlen[i+1] + global_stones[i].len;

	// IKUZO----
	//int t = n / 8;

#pragma omp parallel for num_threads(4)
	for (i=0; i<4; i++) {
		int *p = &global_tmpmap[i << 10];
		memcpy(p, map, 4096);
		backTracking(i, p, global_best.score, 1);
	}

	return EXIT_FAILURE;
}
Ejemplo n.º 5
0
 void backTracking(vector<int>& nums, vector<int> &trace, int start, vector<vector<int>> &res) {
     res.push_back(trace);
     for (int i = start; i < nums.size(); i++) {
         if (i > start && nums[i] == nums[i - 1]) { //用这个剪枝函数来避免同一层节点的重复
             continue;
         }
         trace.push_back(nums[i]);
         
         backTracking(nums, trace, i + 1, res);
         
         trace.pop_back();
     }
 }
/***************************************************************************************
 *	@function : Implementation of 0/1 Knapsack Backtracking method. 
 *	@param: w - weights of n items 
 * 	@param: p - profits of n items
 *	@param: i - Counter (Initially 0)
 *	@param: profit - Profit of 1st item 
 *	@param: weight - Weight of 1st item
 *	@return: void
 ***************************************************************************************/
void backTracking(int *w, int *p, int i, int profit, int weight)
{

	if(weight<=capacity && profit>maxProfit)
	{
		int i;
		maxWeight=weight;
		maxProfit=profit;
		for(i=0;i<50;i++)			
			{	
				bestSet[i] = include[i];
				//printf("%d",include[i] );
			}
	}
	bool isPromising=promising(w,p,i,profit,weight);	
	
	if(isPromising)
	{
		include[cnt++] = 1;
		backTracking(w,p,i+1,profit+p[i+1],weight+w[i+1]); 
		include[cnt++] = 0;
		backTracking(w,p,i+1,profit,weight);
	}
}
Ejemplo n.º 7
0
void backTracking(int l, int n, int k, int curr, int *oneAns, int *used, Result *result) {
    if (curr >= k) {
        memcpy(result->ans[result->size], oneAns, sizeof(int)* k);
        result->size += 1;
        return;
    }
    for (int i = l; i < n; ++i) {
        if (!used[i]) {
            used[i] = 1;
            oneAns[curr] = i + 1;
            backTracking(i + 1, n, k, curr + 1, oneAns, used, result);
            used[i] = 0;
        }
    }
}
Ejemplo n.º 8
0
 void backTracking (const string& s, vector<vector<int> >&prev, int index, vector<string>& output){
   for (int i=0; i<prev[index].size(); ++i){
     int prev_index = prev[index][i];
     vector<string> prev_output(0);
     if (prev_index != 0)
       backTracking (s, prev, prev_index, prev_output);
     else
       prev_output = vector<string> (1, "");
     for (int j=0; j<prev_output.size(); ++j){
       if (prev_index != 0)
         output.push_back(prev_output[j]+" "+s.substr(prev_index,index-prev_index));
       else
         output.push_back(s.substr(prev_index,index-prev_index));
     }   
   }        
 }   
Ejemplo n.º 9
0
 vector<string> wordBreak(string s, unordered_set<string> &dict) {
   // Note: The Solution object is instantiated only once and is reused by each test case.
   int n = s.size();
   if (n == 0) return vector<string> (0);
   vector<vector<int> > dp_prev(n+1, vector<int> (0));//dp_prev[k] has all the prev nodes for substr(0,k-1)
   dp_prev[0] = vector<int> (1,-1);//assign any number to it make it valid
   for (int i=1; i<n+1; ++i){
     for (int j=0; j<i; ++j){
       if (dp_prev[j].size()>0 && dict.find(s.substr(j,i-j))!=dict.end()){
         dp_prev[i].push_back(j);
       }   
     }   
   }   
   //backtracking
   vector<string> output(0);
   backTracking (s, dp_prev, n, output);
   return output;
 }   
Ejemplo n.º 10
0
void Puntaje::inicializar()
{
    Maximo=0;
    matrizBase[1][1]=10;
    matrizBase[1][2]=-1;
    matrizBase[1][3]=-3;
    matrizBase[1][4]=-4;

    matrizBase[2][1]=-1;
    matrizBase[2][2]=7;
    matrizBase[2][3]=-5;
    matrizBase[2][4]=-3;

    matrizBase[3][1]=-3;
    matrizBase[3][2]=-5;
    matrizBase[3][3]=9;
    matrizBase[3][4]=0;

    matrizBase[4][1]= -4;
    matrizBase[4][2]= -3;
    matrizBase[4][3]= 0;
    matrizBase[4][4]= 8;

    resultado1="";
    resultado2="";

    //creacion de la matriz
    array2D.resize(vecta.size ());
    for (int i = 0; i < vecta.size (); i++)
        array2D[i].resize(vectb.size ());

    //rellenando la matriz con los -5
    array2D[0][0]=0;
    for(int i=1;i<array2D[0].size();i++){
        array2D[0][i]=i*-5;
    }
    for(int i=1;i<array2D.size ();i++){
        array2D[i][0]=i*-5;
    }
    generarPuntage ();
    backTracking ();
}
State* SearchTree::backTracking(State* root)
{
    ++visited;

    if(root->countConflicts() == 0)
        return root;

    State *child;

    while ((child = root->makeNextChild()) && child != nullptr)
    {
        ++expanded;

        child = backTracking(child);

        if (child != nullptr)
            return child;
    }

    return nullptr;
}
std::vector<State*> SearchTree::doSearch(std::string algorithm)
{
    double startT, finishT;
    #ifdef __unix
    timespec startWallTime, finishWallTime;
    clock_gettime(CLOCK_MONOTONIC, &startWallTime);
    #else
    GET_TIME(startT);
    #endif
    std::clock_t startCpuTime = std::clock();

    if (algorithm == "bcktrk")
        solution = backTracking(root);
    else if (algorithm == "dfs")
        solution = depthFirstSearch(dfsDepthLimit);
    else if (algorithm == "bfs")
        solution = breadthFirstSearch();
    else if (algorithm == "ucs")
        solution = orderSearch();
    else if (algorithm == "greedy")
        solution = greedy();
    else if (algorithm == "astr")
        solution = AStar();
    else if (algorithm == "idastr")
        solution = IDAStar();

    searchCpuTime = (std::clock() - startCpuTime) / (double)CLOCKS_PER_SEC;
    #ifdef __unix
    clock_gettime(CLOCK_MONOTONIC, &finishWallTime);
    searchWallTime = (finishWallTime.tv_sec - startWallTime.tv_sec) + (finishWallTime.tv_nsec - startWallTime.tv_nsec) / 1000000000.0;
    #else
    GET_TIME(finishT);
    searchWallTime = finishT - startT;
    #endif
    return getPathTo(solution);
}
/***************************************************************************************
 *	@function : Start of the program
 *	@param : argc - Number of arguements. 
 *	@param : argv - argument array
 *	@return: int - returns 0 on successfuly completion.
 ***************************************************************************************/
int main(int argc, char *argv[])
{
 	
 	if(argc != 2)
    {
        printf("Invalid number of argument \nUsage: ./backtrack.out <filename>\n");
        exit(0);
    }

	char *fileName = argv[1];

	//This is used to get the number of items. 
	fileRead(fileName);

	//Create weight and profit array depepeding upon the number of items.
	int *w = malloc(n* sizeof(int));
	int *p = malloc(n* sizeof(int));
	int i,j;

	for(i=0;i<50;i++)
	{
		include[i] = -1;
		bestSet[i] = -1;
	}
	
	//From the given file, get the weights, profits and knapsack capacity.
	getWPC(fileName,w,p);

	/*	 Printing weights and profits of n items
	for(int i=0;i<n;i++)
		printf("%d ", w[i]);
	printf("\n");

	for(int i=0;i<n;i++)
		printf("%d ", p[i]);
	printf("\n");
	*/

	//Weight Temp to get the index of which item to include.
	int *wTemp = malloc(n* sizeof(int));
	for(i=0;i<n;i++)
		wTemp[i] = w[i];

	for(i=0;i<50;i++){
		for(j=0;j<2;j++){
				solution[i][0] = i;
				solution[i][1] = i;
		}
	}
	
	//Step 1: Sort in non-ascending order
	sortProfitWeight(w,p);


	
	//Step 2: Call the Knapsack Back Tracking method. 
	backTracking(w,p,-1,0,0);

	//Step 3: Output into a file.
	outputFile("backtrack_output.txt", maxWeight, maxProfit, bestSet, w, wTemp, solution);


	// Uncomment this to see the output on the screen
	
	printf("Maximum Weight: %d\n", maxWeight);
	printf("Maximum Profit: %d\n", maxProfit);

	/*
	for(i=0;i< n;i++ ){
		for(j=0;j<2;j++){
			printf("%d ", solution[i][j]);
		}
	printf("\n");
	}
	*/
	
	int *tempArray = (int *)malloc(n* sizeof(int));
	for(i=0;i< n;i++ )
		tempArray[i] = 999;

	for(i=0;i<50; i++){
		if(bestSet[i] == 1)
			tempArray[i] = solution[i][1];
	}
	for (i = 0; i < n; ++i)
	{
		for (j = 0; j < i; ++j)
		{
			
			if (tempArray[j]>tempArray[j+1])
			{
				int temp=tempArray[j];
				tempArray[j]=tempArray[j+1];
				tempArray[j+1]=temp;
			}
		}
	}

	printf("Items included: ");
	for( i=0;i<n;i++)
	{
		if(tempArray[i] == 999) break;
		if(tempArray[i+1] == 999)
			printf("%d", tempArray[i]);
		else printf("%d, ", tempArray[i]);
	}
	printf("\n");
	

 	return 0;
}
Ejemplo n.º 14
0
void backTracking(int id, int *map, int nowscore, int first_flg)
{
	int len;

	if (id >= global_n) return;
	if (bestScore2(&global_best, map, &len)) {
		printf("Update best score: (%d, %d)\n", global_best.score, global_best.zk);
		sendMsg("S");
		sendAnswer(global_best.map, global_stones, global_original_stones, global_n);
		if (sendMsg("E") == EXIT_FAILURE) return;
	}
	if ((nowscore - global_sumlen[id]) > global_best.score) return;
	//if (isTraveled(map, id, global_x1, global_y1, global_x2, global_y2, len)) return;

	if (len == 0) return;
	if (len >= global_stones[id].len) {
		int x, y, i, j;

		for (y=global_y1; y<global_y2; y++) {
			for (x=global_x1; x<global_x2; x++) {
				int bidx = (y << 5) + x;
				if (map[bidx] == -2 || map[bidx] >= 0) continue;

				int *p = &global_operation[id << 8];
				len = *p;

				for (i=0; i<len; i++) {
					int xy[32];
					int *pp = &p[i << 5];
					int flg = first_flg || (map[bidx] < -2);

					for (j=1; j<global_stones[id].len; j++) {
						int xx = x + pp[j << 1];
						int yy = y + pp[(j << 1) + 1];
						if (isInValid(xx, yy, global_x1, global_y1, global_x2, global_y2)) goto DAMEDESU;

						int idx = (yy << 5) + xx;
						if (map[idx] == -2 || map[idx] >= 0) goto DAMEDESU;

						xy[j << 1] = xx;
						xy[(j << 1) + 1] = yy;
						flg |= (map[idx] < -2);
					}
					if (!flg) continue;

					// Put
					xy[0] = x;
					xy[1] = y;
					int org[16];

					putStone(map, xy, global_stones[id].len, id, org, global_x1, global_y1, global_x2, global_y2);

					// Recursive
					backTracking(id+1, map, nowscore - global_stones[id].len, 0);

					// Restore
					restoreStone(map, xy, global_stones[id].len, id, org, global_x1, global_y1, global_x2, global_y2);
				DAMEDESU:
					continue;	// noop
				}
			}
		}
	}

	backTracking(id+1, map, nowscore, first_flg);
}