int main() {
		int tc, i, j,x;
		cin >> n >> m;
		
		vector <int> row;

		for (i = 0; i < n; i++) {
			row.clear();
			for (j = 0; j < m; j++) {
				cin >> x;
				row.push_back(x);
			}
			board.push_back(row);
		}



		cin >> tc;

		int stx, sty, enx, eny;
		while (tc--) {
			double sol = 0;
			double sol5 = 0;
			double sol2 = 0;
			double sol3 = 0;
			double sol4 = 0;
			int sol1;
			mp.clear();
			mp1.clear();
			cin >> stx >> sty;
			
			while (!pq.empty())
				pq.pop();
			enx = 0;
			eny = 0;
			sol = getdis(stx, sty, enx, eny);
			
		//	cout << sol << endl;
			mp.clear();
			mp1.clear();

			while (!pq.empty())
				pq.pop();
			enx = 0;
			eny = m - 1;
			sol2 = getdis(stx, sty, enx, eny);
		//	cout << sol << endl;
			mp.clear();
			mp1.clear();

			while (!pq.empty())
				pq.pop();
			enx = n - 1;
			eny = m - 1;
			sol3 = getdis(stx, sty, enx, eny);
		//	cout << sol << endl;
			mp.clear();
			mp1.clear();

			while (!pq.empty())
				pq.pop();
			enx = n - 1;
			eny = 0;
			sol4 = getdis(stx, sty, enx, eny);
			//cout << sol << endl;
			mp.clear();
			mp1.clear();

			sol5 = min(min(sol, sol2), min(sol3, sol4));
			cout << (int)(sol5 + 0.5) << "\n";
		}
		return 0;
}
Esempio n. 2
0
template<class T> inline void CLR(priority_queue<T, vector<T>, greater<T> > &Q){while (!Q.empty()) Q.pop();}
void work()
{
    NODE tmpNode;
    while(!q.empty())
    {
        tmpNode = q.top();
        q.pop();
        //cout<<tmpNode.step<<" "<<tmpNode.val<<endl;
        if(tmpNode.val==0)
        {
            cout<<tmpNode.step<<endl;
            return;
        }
        else
        {
            int tmpx=tmpNode.x;
            int tmpy=tmpNode.y;
            if(tmpx>0)
            {
                node = tmpNode;
                int pos1=tmpx*3+tmpy;
                int pos2=(tmpx-1)*3+tmpy;
                swap(node.str[pos1],node.str[pos2]);
                node.x=tmpx-1;
                node.y=tmpy;
                node.step++;
                node.val = Astar(node);
                if(check(node.str))
                {
                    q.push(node);
                    s.insert(node.str);
                }
            }
            if(tmpx<2)
            {
                node = tmpNode;
                int pos1=tmpx*3+tmpy;
                int pos2=(tmpx+1)*3+tmpy;
                swap(node.str[pos1],node.str[pos2]);
                node.x=tmpx+1;
                node.y=tmpy;
                node.step++;
                node.val = Astar(node);
                if(check(node.str))
                {
                    q.push(node);
                    s.insert(node.str);
                }
            }
            if(tmpy>0)
            {
                node = tmpNode;
                int pos1=tmpx*3+tmpy;
                int pos2=tmpx*3+tmpy-1;
                swap(node.str[pos1],node.str[pos2]);
                node.x=tmpx;
                node.y=tmpy-1;
                node.step++;
                node.val = Astar(node);
                if(check(node.str))
                {
                    q.push(node);
                    s.insert(node.str);
                }
            }
            if(tmpy<2)
            {
                node = tmpNode;
                int pos1=tmpx*3+tmpy;
                int pos2=tmpx*3+tmpy+1;
                swap(node.str[pos1],node.str[pos2]);
                node.x=tmpx;
                node.y=tmpy+1;
                node.step++;
                node.val = Astar(node);
                if(check(node.str))
                {
                    q.push(node);
                    s.insert(node.str);
                }
            }
        }
    }
    cout<<"-1"<<endl;
}
template<class T0, class T1, class T2> inline void CLR(priority_queue<T0, T1, T2> &Q){while (!Q.empty()) Q.pop();}
Esempio n. 5
0
int main() {
	int parent[50];
	string line;
	string FILENAME = "input.txt";
	ifstream istream;

    int i, w, sz;
	char dir, starting = ' ';
    istream.open(FILENAME.c_str());
	if(istream.fail())
	{
		printf("Bad File name. Check readme for example.\n");
	}
	else{
		getline(istream,line);
		istringstream iss(line);
		iss>>dir;

		while(getline(istream,line)){
				
               istringstream iss(line);
               while(iss>>u>>v>>w){
					if(starting == ' '){
						starting = u;
						n.push_back(u);}

						if(std::find(n.begin(), n.end(), v) != n.end()) {
							/* n contains v */
							
						} else {
							/* n does not contain v */
							n.push_back(v);
						}

				  		G[u].push_back(pci(v, w));
						edges++;
					
					if(dir != 'D'){
						G[v].push_back(pci(u, w)); // for undirected
						edges++;
						}
			   }
        }
		nodes = n.size();
		
		
		
		// initialize graph
    for(i=1; i<=nodes; i++) D[n[i-1]] = INF;
   D[starting] = 0;
   Q.push(pci(starting, 0));


    // dijkstra
    while(!Q.empty()) {
       
		u = Q.top().first;
		
        Q.pop();
       
		if(F[u]){ 
			continue;
		}
        
		sz = G[u].size();
	
		for(i=0; i<sz; i++) {
            v = G[u][i].first;
            w = G[u][i].second;
			
 
			if(!F[v] && D[u]+w < D[v]) {
				
				
				D[v] = D[u] + w;
				
                Q.push(pci(v, D[v]));
				
				parent[v]  = u;
				
								
            }
        }
			
			F[u] = 1; 
    }
	
    // result
	printf("Dijkstra\nSource : %c\n", (char)n[0]);
    for(i=1; i<=nodes; i++){ 
		printf("Node %c : %d\n", (char)n[i-1], D[n[i-1]]);
	}
	printf("End Dijkstra\n");

	
	print(parent);
    }
	

	
	
  
    return 0;
}
Esempio n. 6
0
// Total-order deliver for order packets.
// msg -> pointer to msg object
void to_order_deliver(TO_Order * msg) {
	if( ntohl( msg->totalSeqNum ) > receiveSeqNum ) {
		orderBuffer.push( *msg );
	} else if( ntohl( msg->totalSeqNum ) == receiveSeqNum ) {

		unsigned int source_pid = ntohl( msg->pid );

		if( toMsgBuffers[ source_pid ].empty() ) {
			orderBuffer.push( *msg );
			return;
		}

		bool found = false;
		unsigned int seqNum = ntohl( msg->seqNum );
		forward_list<TO_Msg>::iterator iter;
		for( iter = toMsgBuffers[ source_pid ].begin(); iter != toMsgBuffers[ source_pid ].end(); iter++ ) {
			if( ntohl(iter->seqNum) == seqNum ) {

				receiveSeqNum++;

				pthread_mutex_lock( &console_lock );

				// Get current system time
				time_t tt = time(NULL);
				struct tm * tm_struct = localtime(&tt);
				char time_str[9];
				sprintf(time_str, "%d:%d:%d", tm_struct->tm_hour, tm_struct->tm_min, tm_struct->tm_sec);

				// Deliver the message to the application
				char buffer[PAYLOAD+1];
				memcpy( buffer, iter->buf, ntohl(iter->length) );
				buffer[ ntohl(iter->length) ] = '\0';
				printf("Delivered \"%s\" from process %d, system time is %s\n", buffer, source_pid, time_str);

				// Check if there are any other messages to be delivered
				while( !orderBuffer.empty() ) {

					if( ntohl( orderBuffer.top().totalSeqNum ) != receiveSeqNum ) break;

					bool found2 = false;
					unsigned int source_pid2 = ntohl( orderBuffer.top().pid );
					unsigned int seqNum2 = ntohl( orderBuffer.top().seqNum );
					forward_list<TO_Msg>::iterator iter2;
					for( iter2 = toMsgBuffers[ source_pid2 ].begin(); iter2 != toMsgBuffers[ source_pid2 ].end(); iter2++ ) {
						if( ntohl(iter2->seqNum) == seqNum2 ) {
							memcpy( buffer, iter2->buf, ntohl(iter2->length) );
							buffer[ ntohl(iter2->length) ] = '\0';
							printf("Delivered \"%s\" from process %d, system time is %s\n", buffer, source_pid2, time_str);

							orderBuffer.pop();
							receiveSeqNum++;
							found2 = true;
							break;
						}
					}

					if( !found2 ) break;

				}

				pthread_mutex_unlock( &console_lock );

				found = true;
				break;

			}
		}
		if( !found ) {
			orderBuffer.push( *msg );
		}

	}
	// Do nth if we have already seen the order packet before
}
Esempio n. 7
0
int main () {
    while (scanf("%d %d", &v, &e) && v && e) {
        scanf("%d %d", &c, &f);

        for (int i = 0; i < v; i++) {
            verts[i].n = i;
            verts[i].s = -1;
            for (int j = 0; j < v; j++) adj[i][j].clear();
        }

        for (int i = 0; i < e; i++) {
            scanf("%d %d %d", &a, &b, &w);
            adj[a][b].push_back(w);
        }

        verts[c].s = 0;
        fila.push(verts[c]);

        while (!fila.empty()) {
            act = fila.top();
            fila.pop();
            for (int i = 0; i < v; i++) {
                for (int j = 0; j < adj[act.n][i].size(); j++) {
                    if (verts[i].s == -1 || adj[act.n][i][j] + act.s < verts[i].s) {
                        verts[i].s = adj[act.n][i][j] + act.s;
                        fila.push(verts[i]);
                    }
                }
            }
        }
        
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                for (int k = 0; k < adj[i][j].size(); k++) {
                }
            }
        }

        bfs(f);

        for (int i = 0; i < v; i++) verts[i].s = -1;
        verts[c].s = 0;
        fila.push(verts[c]);

        while (!fila.empty()) {
            act = fila.top();
            fila.pop();
            if (act.n == f) break;
            
            for (int i = 0; i < v; i++) {
                for (int j = 0; j < adj[act.n][i].size(); j++) {
                    if (adj[act.n][i][j] == -1) continue;
                    if (verts[i].s == -1 || adj[act.n][i][j] + act.s < verts[i].s) {
                        verts[i].s = adj[act.n][i][j] + act.s;
                        fila.push(verts[i]);
                    }
                }
            }
        }
        
        while (!fila.empty()) {
            fila.pop();
        }

        printf("%d\n", verts[f].s);
    }
}
Esempio n. 8
0
void mergeFiles()
{
    int sizeOutBuffer = 0.2 * RAM;
    
    int numOB = sizeOutBuffer/recordSize;
    
    
    double x = ((double)((RAM-sizeOutBuffer)/NumBlocks));
    int numFilePtr = x/recordSize;
  
    // Store all file pointers in an array
    ifstream *file ;
    string str;
    for(int i=0; i<recordSize; i++) 
    {
        str = to_string(i+1);
        file = new ifstream(("split/file" + str).c_str());
        filePointers.push_back(file);
    }

    ifstream *fptr;
    string line;
    vector<string> record;
    int counter = 0;
    int countOutBuff = 0;
    
    for(int i=0; i<NumBlocks; i++)
    {
        fptr = filePointers[i];
        counter = 0;      
        
        while(getline(*fptr, line)) 
        {
            
            record = split(line, ',');
            maxheap.push(make_pair(record, i));
            ++counter;
            if (counter  == numFilePtr)
                break;
            
        }
    }
    

    
    ofstream outFile;
    outFile.open(HashMapArgs["output_file"]);
    string tempR;
    pair<vector<string>, int> mypair;
    vector<vector<string> > Records;

   
    while(!maxheap.empty()) 
    {
        mypair = maxheap.top();
        maxheap.pop();
        Records.push_back(mypair.first);
        
        // add new record from filepointer to heap
        if (getline(*filePointers[mypair.second], line))
        {
            record = split(line, ',');
            maxheap.push(make_pair(record, mypair.second));
        } 

        countOutBuff=1+countOutBuff;

        if (countOutBuff == numOB) 
        {
            
            for(int i=0; i<Records.size(); i++)
            {
                // only put specific columns into the file
                str = Records[i][ColsIndex[0]];

                for(int j=1; j<ColsIndex.size(); j++)
                    str += "," + Records[i][ColsIndex[j]];
                
                str = str + "\n";
                outFile << str;
            }

            
        }   
    }

    
    if (countOutBuff < numOB)
    {
        
        for(int i=0; i<Records.size(); i++)
        {
            str = Records[i][ColsIndex[0]];
            
            for(int j=1; j<ColsIndex.size(); j++) 
                str += "," + Records[i][ColsIndex[j]];
            
            str += "\n";
            outFile << str;
        }
        Records.clear();
        countOutBuff = 0;
     
    }

    int i=0;
    while(i<NumBlocks) 
        delete filePointers[i++];    
    
    outFile.close();
    filePointers.clear();
}
int main()
{
	picdir = "D:\\CNN\\0728\\CNN1\\0728\\res96\\";
	for (int i = st; i <= en; i++)
	{
		cout << i << "\n";
		char fitname[111];
		sprintf(fitname, "%s%d%s", "D:\\CNN\\c++gaussianfit\\fit", i, ".txt");
		FILE *foutfit = fopen(fitname, "w");
		choose = (int *)malloc(sizeof(int)*(JOINT + 1));
		tchoose = (int *)malloc(sizeof(int)*(JOINT + 1));
		for (int joint = 0; joint <= 13; joint++)
		{
			char heatmapname[MaxLen];
			sprintf(heatmapname,"%s%d_%d%s", "D:\\CNN\\CNN1\\results\\r_", i, joint, ".png");
			Mat img = imread(heatmapname);					
			int pmin = 11111, pmax = 0;
			//Find Maximum & Minimum
			fprintf(foutfit, "%d : \n", joint);
			for (int k = 0; k < Height; k++)
			{
				for (int l = 0; l < Width; l++)
				{					
					pmax = max(pmax, (int)img.at<cv::Vec3b>(k, l)[0]);
					pmin = min(pmin, (int)img.at<cv::Vec3b>(k, l)[0]);
				}
			}						
			int id=0;
			for (int k = 1; k <= Height; k++)
			{
				for (int l = 1; l <= Width; l++)
				{
					z[k][l] =(double) (img.at<cv::Vec3b>(k-1, l-1)[0] - pmin) / (double)(pmax - pmin);										
					savez[k][l] = z[k][l];
					pixel[id].data = z[k][l]; pixel[id].x = l; pixel[id++].y = k;
				}											
			}			
			//Sort by pixel intensity
			sort(pixel, pixel + Height*Width, cmp);
			int maxrow[NUM + 1], maxcol[NUM + 1];
			memset(used, 0, sizeof(used));
			for (int j = 1; j <= NUM; j++) maxrow[j] = maxcol[j] = -1;
			int num = 1;
			//Top Num Peak
			for (int j = 0; j < Height*Width && num<=NUM;j++)
			{
				if (used[pixel[j].y][pixel[j].x]) continue;
				maxrow[num] = pixel[j].y; maxcol[num] = pixel[j].x;				
				value[joint + 1][num] = pixel[j].data;
				for (int irow = max(1, maxrow[num] - 1); irow <= min(3 - (maxrow[num] - max(1, maxrow[num] - 1) + 1) + maxrow[num], 22); irow++)
				{
					for (int icol = max(1, maxcol[num] - 1); icol <= min(3 - (maxcol[num] - max(1, maxcol[num] - 1) + 1) + maxcol[num], 22); icol++)
					{
						used[irow][icol] = 1;
					}
				}
				num++;
			}
			int T = 2;
			for (num = 1; num <= NUM; num++)
			{
				//fprintf(foutfit, "        %d.   \n", num);
				if (maxrow[num] == -1) continue;
				int row1 = max(1, maxrow[num] - T), row2 = min(2 * T + 1 - (maxrow[num] - max(1, maxrow[num] - T) + 1) + maxrow[num], 22);
				int col1 = max(1, maxcol[num] - T), col2 = min(2 * T + 1 - (maxcol[num] - max(1, maxcol[num] - T) + 1) + maxcol[num], 22);
				double fmax = 0.0;
				pixeltype tmp[26];
				int id = 26;
				tmp[0].data = 0.0;
				q1.empty();
				q2.empty();
				for (int irow = 1; irow <= Height; irow++)
				{
					for (int icol = 1; icol <= Width; icol++)
					{
						if (irow >= row1 && irow <= row2 && icol >= col1 && icol <= col2)
						{
							z[irow][icol] = savez[irow][icol];
							q1.push(QMAX(icol, irow, z[irow][icol]));							
							q2.push(QMIN(icol, irow, z[irow][icol]));
							
						}
						else z[irow][icol] = 0.0;
						
					}
				}								
				if (joint == 2 && num == 7)
				{
					//cout << "----";
				}
				double maxrsquare = -11111.0;
				double maxx0, maxy0;
				xx0 = maxcol[num]; yy0 = maxrow[num];
				a1 = 1.0; sigma = 1.0; lastrsquare = 0.0;
				for (int iter = 1; iter <= 30; iter++)
				{
					init(z);
					getcenterpoint();
					computefitness();
					if (rsquare - lastrsquare < 1e-3) break;
					lastrsquare = rsquare;
				}
				if (rsquare - maxrsquare>eps) { maxrsquare = rsquare; maxx0 = xx0; maxy0 = yy0; }
				//fprintf(foutfit, "    %4d %4d %4d %12.6f %12.6f %12.6f %12.6f %12.6f\n", joint, num, 0, maxrsquare, xx0, yy0, a1, sigma);				
				if (!(maxrsquare - 0.80 > eps))
				{
					for (int j = 1; j <= 13; j++)
					{
						for (int t = 0; t <= 1; t++)
						{
							if (t == 0)
							{
								QMAX now = q1.top();
								q1.pop();
								xx0 = now.x; yy0 = now.y;
							}//forward
							else
							{
								QMIN now = q2.top();
								q1.pop();
								xx0 = now.x; yy0 = now.y;
							}//backward
							a1 = 1.0; sigma = 1.0; lastrsquare = 0.0;
							for (int iter = 1; iter <= 30; iter++)
							{
								init(z);
								getcenterpoint();
								computefitness();
								if (rsquare - lastrsquare < 1e-3) break;
								lastrsquare = rsquare;
							}
							if (rsquare - maxrsquare>eps) { maxrsquare = rsquare; maxx0 = xx0; maxy0 = yy0; }
							//fprintf(foutfit, "    %4d %4d %4d %12.6f %12.6f %12.6f %12.6f %12.6f\n", joint, num,(t==0?j:26-j), rsquare, xx0, yy0, a1, sigma);
						}
						if (maxrsquare - 0.80 > eps)
						{
							break;
						}
					}					
				}				
				//fprintf(foutfit, "\n\n");
				peakrsquare[joint + 1][num] = maxrsquare; peakx0[joint + 1][num] = maxx0; peaky0[joint + 1][num] = maxy0;				
			}		
			for (num = 1; num <= NUM; num++)
			{
				fprintf(foutfit, "    %d.%12.6f %12.6f %12.6f %12.6f\n", num, value[joint + 1][num], peakx0[joint + 1][num], peaky0[joint+ 1][num],peakrsquare[joint + 1][num]);
			}
			double fminrsquare = 11111.0;
			for (num = 1; num <= NUM; num++)
			{
				if (1.0 - peakrsquare[joint + 1][num]<fminrsquare && value[joint + 1][num]>MINLIGHT)
				{
					fminrsquare = 1.0 - peakrsquare[joint + 1][num];
					tchoose[joint+1]=choose[joint + 1] = num;
				}
			}	
			fprintf(foutfit, "\n");
		}
		fclose(foutfit);
		char oripic[111];
		sprintf(oripic, "%s%d%s", picdir, i + 1, ".png");
		Mat pic = imread(oripic);
		resize(pic, pic, Size(96, 96));
		//thumb first
		choose = modifythumb(choose, value, peakrsquare, pic, peakx0, peaky0, 0, 0, 0);
		//middle second
		choose = modifymiddle(choose, value, peakrsquare, pic, peakx0, peaky0, 0, 0);
		//up third
		choose = modifyup(choose, value, peakrsquare, pic, peakx0, peaky0, 0, 0);
		/////Finger 3 4 5 should be at the left of palm
		int thumbleftarea = 0,thumbrightarea = 0;
		if (peakx0[6 + 1][choose[6 + 1]]>peakx0[8 + 1][choose[8 + 1]] && peakx0[8 + 1][choose[8 + 1]]>peakx0[10 + 1][choose[10 + 1]] && peakx0[10 + 1][choose[10 + 1]]>peakx0[12 + 1][choose[12 + 1]] &&
			peakx0[7 + 1][choose[7 + 1]]>peakx0[9 + 1][choose[9 + 1]] && peakx0[9 + 1][choose[9 + 1]]>peakx0[11 + 1][choose[11 + 1]] && peakx0[11 + 1][choose[11 + 1]]>peakx0[13 + 1][choose[13 + 1]] &&
			peakx0[3 + 1][choose[3 + 1]]>peakx0[0 + 1][choose[0 + 1]] && peakx0[4 + 1][choose[4 + 1]]>peakx0[0 + 1][choose[0 + 1]] && peakx0[5 + 1][choose[5 + 1]]>peakx0[0 + 1][choose[0 + 1]])
			thumbleftarea = 1;
		/////Finger 3 4 5 should be at the right of palm
		if (peakx0[6 + 1][choose[6 + 1]]<peakx0[8 + 1][choose[8 + 1]] && peakx0[8 + 1][choose[8 + 1]]<peakx0[10 + 1][choose[10 + 1]] && peakx0[10 + 1][choose[10 + 1]]<peakx0[12 + 1][choose[12 + 1]] && 
			peakx0[7 + 1][choose[7 + 1]]<peakx0[9 + 1][choose[9 + 1]] && peakx0[9 + 1][choose[9 + 1]]<peakx0[11 + 1][choose[11 + 1]] && peakx0[11 + 1][choose[11 + 1]]<peakx0[13 + 1][choose[13 + 1]] && 
			peakx0[3 + 1][choose[3 + 1]]<peakx0[0 + 1][choose[0 + 1]] && peakx0[4 + 1][choose[4 + 1]]<peakx0[0 + 1][choose[0 + 1]] && peakx0[5 + 1][choose[5 + 1]]<peakx0[0 + 1][choose[0 + 1]])
			thumbrightarea = 1;

		if (thumbleftarea == 0 && thumbrightarea == 0)
		{
			if (peakx0[3 + 1][choose[3 + 1]]<peakx0[0 + 1][choose[0 + 1]] && peakx0[4 + 1][choose[4 + 1]]<peakx0[0 + 1][choose[0 + 1]] && peakx0[5 + 1][choose[5 + 1]]<peakx0[0 + 1][choose[0 + 1]])
				thumbleftarea = 1;
			else
			{
				if (peakx0[3 + 1][choose[3 + 1]]>peakx0[0 + 1][choose[0 + 1]] && peakx0[4 + 1][choose[4 + 1]]>peakx0[0 + 1][choose[0 + 1]] && peakx0[5 + 1][choose[5 + 1]]>peakx0[0 + 1][choose[0 + 1]])
					thumbrightarea = 1;
			}
		}
		/////Modify thumb middle up
		if (thumbleftarea!= 0 || thumbrightarea!= 0)
		{
			choose = modifythumb(choose, value, peakrsquare, pic, peakx0, peaky0, thumbleftarea, thumbrightarea, 0);
			choose = modifymiddle(choose, value, peakrsquare, pic, peakx0, peaky0, thumbleftarea, thumbrightarea);
			choose = modifyup(choose, value, peakrsquare, pic, peakx0, peaky0, thumbleftarea, thumbrightarea);
		}
		int tooclose = 0;
		for (int j = 6; j <= 13; j++)
		{
			tooclose = 1;
			break;
		}
		/////Finger 3 4 5 should be modified;
		if (tooclose == 1) choose = modifythumb(choose, value, peakrsquare, pic, peakx0, peaky0, thumbleftarea, thumbrightarea, 1);
		/////Check sucess or not
		tooclose = 0;
		for (int j = 6; j <= 13; j++)
		{
			if (computedis2(peakx0[j + 1][choose[j + 1]], peaky0[j + 1][choose[j + 1]], peakx0[3 + 1][choose[3 + 1]], peaky0[3 + 1][choose[3 + 1]])<5.0)
			{
				tooclose = 1;
				break;
			}
		}
		/////Modify 3 4 5 failure
		if (tooclose == 1)
		{
			choose[3 + 1] = tchoose[3 + 1]; choose[4 + 1] = tchoose[4 + 1]; choose[5 + 1] = tchoose[5 + 1];
		}


		for (int j = 0; j <= 13; j++)
		{
			char jointfile[111];
			sprintf(jointfile, "%s%d_%d%s", "D:\\CNN\\c++gaussianfit\\joint\\", i, j, ".txt");
			FILE *foutjoint = fopen(jointfile, "w");
			fprintf(foutjoint, "%.6f %.6f\n", peakx0[j + 1][choose[j + 1]], peaky0[j + 1][choose[j + 1]]);
			fclose(foutjoint);
		}
	}
	showjointonpicture();
	return 0;
}
Esempio n. 10
0
int PalindromizationDiv1::getMinimumCost(string s, vector <string> op) {
    int n = op.size();
    for (int i = 0;i < n;i++)
    {
        if (op[i][0] == 'a')
        {
            sscanf(op[i].c_str(),"%s%s%d",tmp,o[i].c1,&o[i].cost);
            o[i].typ = 0;
        }
        else if (op[i][0] == 'e')
        {
            sscanf(op[i].c_str(),"%s%s%d",tmp,o[i].c1,&o[i].cost);
            o[i].typ = 1;
        }
        else if (op[i][0] == 'c')
        {
            sscanf(op[i].c_str(),"%s%s%s%d",tmp,o[i].c1,o[i].c2,&o[i].cost);
            o[i].typ = 2;
        }
    }
    node now;
    hash.clear();
    while (!Q.empty())  Q.pop();
    Q.push(node(s,0));
    hash.insert(s);
    int tim = 0;
    while (!Q.empty())
    {
        now = Q.top();
        Q.pop();
        if (palindrome(now.now) == true)    return now.cost;
        tmp1 = now.now;
        if (tmp1.size() > s.size()*2)   continue;
        for (int i = 0;i < n;i++)
        {
            if (o[i].typ == 0)
            {
                for (int j = 0;j <= tmp1.size();j++)
                {
                    tmp2 = tmp1.substr(0,j)+o[i].c1[0]+tmp1.substr(j,tmp1.size()-j);
                    if (hash.find(tmp2) == hash.end())
                    {
                        hash.insert(tmp2);
                        Q.push(node(tmp2,now.cost+o[i].cost));
                    }
                }
            }
            else if (o[i].typ == 1)
            {
                for (int j = 0;j < tmp1.size();j++)
                    if (tmp1[j] == o[i].c1[0])
                    {
                        tmp2 = tmp1.substr(0,j)+tmp1.substr(j+1,tmp1.size()-j-1);
                        if (hash.find(tmp2) == hash.end())
                        {
                            hash.insert(tmp2);
                            Q.push(node(tmp2,now.cost+o[i].cost));
                        }
                    }
            }
            else if (o[i].typ == 2)
            {
                for (int j = 0;j < tmp1.size();j++)
                    if (tmp1[j] == o[i].c1[0])
                    {
                        tmp2 = tmp1;
                        tmp2[j] = o[i].c2[0];
                        if (hash.find(tmp2) == hash.end())
                        {
                            hash.insert(tmp2);
                            Q.push(node(tmp2,now.cost+o[i].cost));
                        }
                    }
            }
        }
    }
    return -1;
}
double getdis(int stx, int sty, int enx, int eny) {
    pid ex;
    pq.push(make_pair(0, make_pair(stx, sty)));

    int i;
    int j;

    if (board[stx][sty] == 1) {
        return 0;
    }

    int test;

    while (!pq.empty()) {
        ex = pq.top();
        pq.pop();
        mp1.insert(make_pair(ex.second, 1));
        mp.erase(ex.second);
        i = ex.second.first;
        j = ex.second.second;

        if ((ex.second.first == enx) && (ex.second.second == eny)) {
            return ex.first;
        }

        if ((j + 1 < m) && (board[i][j + 1] == 0) && (mp1.count(make_pair(i, j+1)) == 0)) {
            if (mp.count(make_pair(i, j + 1)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i, j+1)));
                mp.insert(make_pair(make_pair(i,j + 1),ex.first + 1));
            }
            else {
                test = mp[make_pair(i, j + 1)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i, j+1)));
                    mp[make_pair(i,j+1)] = ex.first + 1;
                }
            }
        }

        if (((j + 1 < m) && (i + 1 < n)) && (board[i + 1][j + 1] == 0) && (mp1.count(make_pair(i + 1, j+1)) == 0)) {
            if (mp.count(make_pair(i + 1, j + 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i + 1, j+1)));
                mp.insert(make_pair(make_pair(i + 1,j + 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i + 1, j + 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i+1, j+1)));
                    mp[make_pair(i+1,j+1)] = ex.first + rt2;
                }
            }
        }

        if ((i + 1 < n) && (board[i+1][j] == 0) && (mp1.count(make_pair(i + 1, j)) == 0)) {
            if (mp.count(make_pair(i + 1, j)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i + 1, j)));
                mp.insert(make_pair(make_pair(i + 1,j),ex.first + 1));
            }
            else {
                test = mp[make_pair(i + 1, j)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i + 1, j)));
                    mp[make_pair(i+1,j)] = ex.first + 1;
                }
            }
        }

        if (((j - 1 >= 0) && (i + 1 < n)) && (board[i + 1][j - 1] == 0) && (mp1.count(make_pair(i + 1, j-1)) == 0)) {
            if (mp.count(make_pair(i + 1, j - 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i + 1, j-1)));
                mp.insert(make_pair(make_pair(i + 1,j - 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i + 1, j - 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i+1, j-1)));
                    mp[make_pair(i+1,j-1)] = ex.first + rt2;
                }
            }
        }

        if ((j - 1 >= 0) && (board[i][j - 1] == 0) && (mp1.count(make_pair(i, j-1)) == 0)) {
            if (mp.count(make_pair(i, j - 1)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i, j - 1)));
                mp.insert(make_pair(make_pair(i,j - 1),ex.first + 1));
            }
            else {
                test = mp[make_pair(i, j - 1)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i, j - 1)));
                    mp[make_pair(i,j-1)] = ex.first + 1;
                }
            }
        }

        if (((j - 1 >= 0) && (i - 1 >= 0)) && (board[i - 1][j - 1] == 0) && (mp1.count(make_pair(i-1, j-1)) == 0)) {
            if (mp.count(make_pair(i - 1, j - 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i - 1, j-1)));
                mp.insert(make_pair(make_pair(i - 1,j - 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i - 1, j - 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i-1, j-1)));
                    mp[make_pair(i-1,j-1)] = ex.first + rt2;
                }
            }
        }

        if ((i - 1 >= 0) && (board[i - 1][j] == 0) && (mp1.count(make_pair(i-1, j)) == 0)) {
            if (mp.count(make_pair(i - 1, j)) == 0) {
                pq.push(make_pair(ex.first + 1, make_pair(i - 1, j)));
                mp.insert(make_pair(make_pair(i - 1,j),ex.first + 1));
            }
            else {
                test = mp[make_pair(i - 1, j)];
                if (test > ex.first + 1) {
                    pq.push(make_pair(ex.first + 1, make_pair(i - 1, j)));
                    mp[make_pair(i-1,j)] = ex.first + 1;
                }
            }
        }

        if (((j + 1 < m) && (i - 1 >= 0)) && (board[i - 1][j + 1] == 0) && (mp1.count(make_pair(i - 1, j+1)) == 0)) {
            if (mp.count(make_pair(i - 1, j + 1)) == 0) {
                pq.push(make_pair(ex.first + rt2, make_pair(i - 1, j+1)));
                mp.insert(make_pair(make_pair(i - 1,j + 1),ex.first + rt2));
            }
            else {
                test = mp[make_pair(i - 1, j + 1)];
                if (test > ex.first + rt2) {
                    pq.push(make_pair(ex.first + rt2, make_pair(i-1, j+1)));
                    mp[make_pair(i-1,j+1)] = ex.first + rt2;
                }
            }
        }


    }
}
Esempio n. 12
0
int main() {
	int query_n;
	bool is_queue, is_stack, is_pqueue;

	while (cin >> query_n) {
		is_queue = is_stack = is_pqueue = true;

		while (! S.empty()) S.pop();
		while (! Q.empty()) Q.pop();
		while (!PQ.empty()) PQ.pop();

		bool impossible = false;

		while (query_n--) {
			int q, x;
			cin >> q >> x;

			switch (q) {
				case 1:
					if (is_stack) S.push(x);
					if (is_queue) Q.push(x);
					if (is_pqueue) PQ.push(x);
					break;

				case 2:
					if (is_stack) {
						if (S.empty()) {
							impossible = true;
							break;
						}
						if (S.top() == x)
							S.pop();
						else
							is_stack = false;
					}

					if (is_queue) {
						if (Q.empty()) {
							impossible = true;
							break;
						}
						if (Q.front() == x)
							Q.pop();
						else
							is_queue = false;
					}

					if (is_pqueue) {
						if (PQ.empty()) {
							impossible = true;
							break;
						}
						if (PQ.top() == x)
							PQ.pop();
						else
							is_pqueue = false;
					}
					break;
			}
		}

		if (impossible) {
			cout << "impossible";
		} else
		if (is_queue + is_stack + is_pqueue >= 2) {
			cout << "not sure";
		} else {
			if (is_queue) {
				cout << "queue";
			} else
			if (is_stack) {
				cout << "stack";
			} else
			if (is_pqueue) {
				cout << "priority queue";
			} else {
				cout << "impossible";
			}
		}
		cout << endl;
	}

	return 0;
}
Esempio n. 13
0
void sol(int st, int ed, int n) {
    int v, m = 0, i;
    queue<int> Q;
    Q.push(ed);
    for(i = 1; i <= n; i++)
        used[i] = 0, cdis[i] = dis[i];
    while(!Q.empty()) {
        v = Q.front();
        Q.pop();
        for(it i = g[v].begin();
            i != g[v].end(); i++) {
            if(dis[i->to] == dis[v] - i->w) {
                SEG[m].s = dis[i->to];
                SEG[m].e = dis[v];
                SEG[m].v = v;
                SEG[m++].p = i;
                if(used[i->to] == 0) {
                    used[i->to] = 1;
                    Q.push(i->to);
                }
            }
        }
    }
    sort(SEG, SEG+m, cmps);
    LL ans = 0, odis = dis[ed], tmp;
    it ip;
    int runtime = 0, tj = 0;
    for(i = 0; i < m; i++) {
        while(!pQ2.empty() && SEG[i].s >= pQ2.top().e)
            pQ2.pop();
        tmp = SEG[i].s;
        while(i < m && SEG[i].s == tmp)
            pQ2.push(SEG[i]), i++;
        i--;
        if(pQ2.size() == 1) {
            SEG[tj++] = SEG[i];
            //printf("%lld %lld\n", SEG[i].s, SEG[i].e);
        }
    }
    while(!pQ2.empty()) pQ2.pop();
    sort(SEG, SEG+tj, cmpw);
    for(i = 0; i < tj; i++) {
        //printf("%lld %lld\n", SEG[i].s, SEG[i].e);
        if(SEG[i].p->w <= ans)
            continue;
        //if(runtime > 3000000)   break;
        for(ip = g[SEG[i].p->to].begin();
            ip != g[SEG[i].p->to].end(); ip++) {
            if(ip->to == SEG[i].v)
                break;
        }
        runtime += n;
        for(int j = 1; j <= n; j++) {
            if(cdis[j] <= SEG[i].s)
                pQ.push(ele(j, cdis[j]));
            else
                dis[j] = cdis[j]+ip->w;
            used[j] = 0;
        }
        SEG[i].p->w *= 2;
        ip->w *= 2;
        tmp = dijkstra(st, ed, n);
        if(tmp - odis >= ans)
            ans = tmp - odis;
        if(ans == ip->w/2)
            break;
        ip->w /= 2;
        SEG[i].p->w /= 2;
        i += rand()%2;
    }
    printf("%lld\n", ans);
}
Esempio n. 14
0
int main(){

//    freopen("~/in","r",stdin);

    scanf("%d %d",&n,&m);
    scanf("%d %d",&x,&y);


    for (int i=0;i<m;i++){
        scanf("%d %d %d",&etmp.st,&etmp.ed,&etmp.length);
        edges[etmp.st].push_back(etmp);
        swap(etmp.st,etmp.ed);
        edges[etmp.st].push_back(etmp);
    }
    for (int i=1;i<=n;i++){
        scanf("%d %d",&dl[i],&ct[i]);
    }



    while(!pq.empty()){
        pq.pop();
    }
    memset(visted,0,sizeof(int)*(n+1));
    memset(shortest,0,sizeof(int)*(n+1));
    memset(sed,0,sizeof(sed));
    shortest[x] = -1;
    ntmp.value = 0;
    ntmp.id = x;
    pq.push(ntmp);
    bool flag = false;
    while(!pq.empty()){
        ntmp = pq.top();
        pq.pop();
        if (ntmp.id==y){
            printf("%I64d\n",ntmp.value);
            flag = true;
            break;
        }
        if (sed[ntmp.id] == true)  continue;
        sed[ntmp.id] = true;

        //扩展路径

        memset(visted,0,sizeof(int)*(n+1));
        roads.clear();
        visted[ntmp.id] = 2000000000;
        spread(ntmp.id,ntmp.id,dl[ntmp.id]);
        itro = roads.begin();
        for (;itro!=roads.end();itro++){
            new_node.id = itro->dest;
            if (new_node.id==ntmp.id) continue;
            new_node.value = itro->cost+ntmp.value;
            if (shortest[new_node.id]==0||new_node.value<shortest[new_node.id]){
                shortest[new_node.id] = new_node.value;
                pq.push(new_node);
            }
        }

    }
    if (flag==false)
        printf("-1\n");
    return 0;
}
Esempio n. 15
0
// A thread that takes packets out from the queue and send them based on their specified delay.
void *p_unicast_send_delay(void * arg) {

	// To allow the thread to be canceled by the main thread
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);

	pthread_mutex_lock( &queue_lock );
	while( true ) {
		if( pktQueue.empty() ) {
			pthread_cond_wait( &queue_cv, &queue_lock ); // wait for the main thread to put a msg into the queue
		}

		bool goToIsEmpty = false;
		while( !goToIsEmpty ) {
			// Calculate delay = scheduled time that the packet should be sent - current time
			long int msgTime = pktQueue.top().timeWhenAdded;
			int msgDelay = pktQueue.top().delay;

		    struct timeval now;
			gettimeofday(&now,NULL);
			long int nowTime = now.tv_sec * 1000 + now.tv_usec / 1000;

			long int delay = msgTime + msgDelay - nowTime;

			if( delay <= 0 ) {

				// May happen in 2 cases:
				// - a newly added msg has delay = 0
				// - there are 2 consecutive msgs
				// Assumption: negligible in unit of second

				// Send the packet
				Q_Packet msgPacket = pktQueue.top();
				pktQueue.pop();
				unicast_send( msgPacket.dest_pid, msgPacket.pkt, msgPacket.length );
				// Go to check if the queue is empty
				goToIsEmpty = true;
				continue;

			} else {

				// Schedule time out
				struct timespec after;
			    long int ns = (now.tv_usec+1000UL*delay)*1000UL;
			    after.tv_sec = now.tv_sec + ns/1000000000UL;
			    after.tv_nsec = ns%1000000000UL;

				int rt = pthread_cond_timedwait( &queue_cv, &queue_lock, &after );

				if( rt == ETIMEDOUT ) {

					// Send the packet
					Q_Packet msgPacket = pktQueue.top();
					pktQueue.pop();
					unicast_send( msgPacket.dest_pid, msgPacket.pkt, msgPacket.length );
					// Go to check if the queue is empty
					goToIsEmpty = true;
					continue;

				} else if( rt == 0 ) {
					// Go to check if the newly-added packet has a negative delay
					continue;
				} else {
					printf("p_unicast_send_delay: pthread_cond_timedwait error: returned %d\n", rt);
					exit(1);
				}
			}
		}
	}
}
Esempio n. 16
0
File: 1103.cpp Progetto: IvanAli/CP
int main() {
	int tc = 0;
	int H, W;
	int ccw, ccb, p;
	for(char i = 'A'; i <= 'z'; i++) {
		id[i - 'A'] = i;
	}
	while(scanf("%d %d", &H, &W) && (H | W)) {
		maxrow = H;
		maxcol = W * 4;
		ccw = 0; ccb = 0; p = 0;
		memset(ws, -1, 58);
		for(int i = 0; i < 58; i++) ws[i] = -1;

		char s[W];
		const char *bin;
		for(int i = 0; i < H; i++) {
			scanf("%s", &s);
			for(int j = 0; j < W; j++) {
				bin = hexToBin(s[j]);
				for(int k = 0; k < 4; k++) {
					image[i][j * 4 + k] = bin[k];
				}
			}
		}

		// algorithm
		bool found = false;
		for(int j = 0; j < maxcol; j++) {
			if(image[0][j] == '0') {
				q.push(ii(0, j));
				floodfill8BFS('0', '.');
			}
			if(image[maxrow - 1][j] == '0') {
				q.push(ii(maxrow - 1, j));
				floodfill8BFS('0', '.');
			}
		}
		for(int i = 0; i < maxrow; i++) {
			if(image[i][0] == '0') {
				q.push(ii(i, 0));
				floodfill8BFS('0', '.');
			}
			if(image[i][maxcol - 1] == '0') {
				q.push(ii(i, maxcol - 1));
				floodfill8BFS('0', '.');
			}
		}
		// floodfill8(0, 0, '0', '.');
		/*for(int i = 0; i < maxrow; i++) {
			for(int j = 0; j < maxcol; j++) {
				printf("%c", image[i][j]);
			}
			printf("\n");
		}*/
		for(int i = 0; i < maxrow; i++) {
			for(int j = 0; j < maxcol; j++) {
				/*if(image[i][j] == '0') {
					floodfill(i, j, '0', '.');
					ccw++;
				}*/
				if(image[i][j] == '1') {
					floodfill(i, j, '1', id[p]);
					ws[p] = 0;
					ccb++;p++;
				}
			}
		}
		char currch;
		for(int i = 0; i < maxrow; i++) {
			for(int j = 0; j < maxcol; j++) {
				// printf("%c", image[i][j]);
				if(!isdigit(image[i][j])) {
					currch = image[i][j];
				}
				if(image[i][j] == '0') {
					// printf("blank at curr char: %c\n", currch);
					q.push(ii(i, j));
					floodfillBFS('0', '.');
					ws[currch - 'A']++;
				}
			}
			// printf("\n");
		}
		for(int i = 0; i < 56; i++) {
			if(ws[i] == 1) pq.push('A');
			if(ws[i] == 3) pq.push('J');
			if(ws[i] == 5) pq.push('D');
			if(ws[i] == 4) pq.push('S');
			if(ws[i] == 0) pq.push('W');
			if(ws[i] == 2) pq.push('K');
		}
		printf("Case %d: ", ++tc);
		while(!pq.empty()) {
			printf("%c", pq.top());
			pq.pop();
		}
		printf("\n");
		// printf("ccw: %d ccb: %d\n", ccw, ccb);

	}


	return 0;
}
Esempio n. 17
0
// Total-order deliver for message packets.
// source_pid -> id of source process
// msg        -> pointer to msg object
void to_msg_deliver(int source_pid, TO_Msg * msg) {
	if( pid == 0 ) { // sequencer

		// Deliver the message to the application
		pthread_mutex_lock( &console_lock );
		time_t tt = time(NULL);
		struct tm * tm_struct = localtime(&tt);
		char time_str[9];
		sprintf(time_str, "%d:%d:%d", tm_struct->tm_hour, tm_struct->tm_min, tm_struct->tm_sec);
		char buffer[PAYLOAD+1];
		memcpy( buffer, msg->buf, ntohl(msg->length) );
		buffer[ ntohl(msg->length) ] = '\0';
		printf("Delivered \"%s\" from process %d, system time is %s\n", buffer, source_pid, time_str);
		pthread_mutex_unlock( &console_lock );

		// Multicast order packet
		for(int p=0; p<PROCESSES; p++) {
			TO_Order * packet = new TO_Order(source_pid, ntohl(msg->seqNum), receiveSeqNum);
			unicast_send_delay( p, packet, sizeof(TO_Order) );
		}
		receiveSeqNum++;

	} else { // receiver

		if( orderBuffer.empty() ) { // waiting for an order packet
			toMsgBuffers[ source_pid ].push_front( *msg );
		} else if( ntohl( orderBuffer.top().totalSeqNum ) != receiveSeqNum ) { // waiting for an order packet
			toMsgBuffers[ source_pid ].push_front( *msg );
		} else { // waiting for the right msg packet

			unsigned int expected_source_pid = ntohl( orderBuffer.top().pid );
			unsigned int seqNum = ntohl( orderBuffer.top().seqNum );
			if( expected_source_pid != (unsigned int) source_pid || seqNum != ntohl(msg->seqNum) ) { // it's not the right msg packet
				toMsgBuffers[ source_pid ].push_front( *msg );
			} else { // it is the right msg packet

				pthread_mutex_lock( &console_lock );

				// Get current system time
				time_t tt = time(NULL);
				struct tm * tm_struct = localtime(&tt);
				char time_str[9];
				sprintf(time_str, "%d:%d:%d", tm_struct->tm_hour, tm_struct->tm_min, tm_struct->tm_sec);

				// Deliver the msg to the application
				char buffer[PAYLOAD+1];
				memcpy( buffer, msg->buf, ntohl(msg->length) );
				buffer[ ntohl(msg->length) ] = '\0';
				printf("Delivered \"%s\" from process %d, system time is %s\n", buffer, source_pid, time_str);

				orderBuffer.pop();
				receiveSeqNum++;

				// Check if there are any other msg to be delivered
				while( !orderBuffer.empty() ) {

					if( ntohl( orderBuffer.top().totalSeqNum ) != receiveSeqNum ) break;

					bool found2 = false;
					unsigned int source_pid2 = ntohl( orderBuffer.top().pid );
					unsigned int seqNum2 = ntohl( orderBuffer.top().seqNum );
					forward_list<TO_Msg>::iterator iter2;
					for( iter2 = toMsgBuffers[ source_pid2 ].begin(); iter2 != toMsgBuffers[ source_pid2 ].end(); iter2++ ) {
						if( ntohl(iter2->seqNum) == seqNum2 ) {
							memcpy( buffer, iter2->buf, ntohl(iter2->length) );
							buffer[ ntohl(iter2->length) ] = '\0';
							printf("Delivered \"%s\" from process %d, system time is %s\n", buffer, source_pid2, time_str);

							orderBuffer.pop();
							receiveSeqNum++;
							found2 = true;
							break;
						}
					}

					if( !found2 ) break;

				}

				pthread_mutex_unlock( &console_lock );

			}

		}

	}
}
Esempio n. 18
0
	bool empty() { return pQueue.empty(); }
Esempio n. 19
0
/**
 * Recursive function to simulate local time-stepping on each refinement level
 * @param i_dt_c the checkpoint interval
 * @return the time that was simulated
 */
float SWE_BlockManager::simulate_level(const float i_dt_c,
									   const int i_level,
									   priority_queue<SWE_BlockAMR*, vector<SWE_BlockAMR*>, CompareSWE_BlockAMR> i_pq) {
	float l_t = 0;
	int l_num_ts = 0;
	// build a temporary vector with the blocks on level l
	vector<SWE_BlockAMR*> l_blocks;
	while (!i_pq.empty() && i_pq.top()->getRefinementLevel() == i_level) {
		if (interpolationScheme == SPACE)
			i_pq.top()->resetComputationalDomainMax();
		l_blocks.push_back(i_pq.top());
		i_pq.pop();
	}
	// time-stepping
	while (l_t < i_dt_c) {
		float l_dt = (float) 600.;
		// update copy and ghost layers by using the two-phase update scheme:

		// 1. update left-right boundary cells
		// update copy layer
		for(vector<SWE_BlockAMR*>::iterator it = l_blocks.begin(); it != l_blocks.end(); ++it) {
			if ((*it)->getNeighbour(BND_LEFT) != NULL)
				(*it)->getNeighbour(BND_LEFT)->synchCopyLayerBeforeRead(LTS, BND_RIGHT, l_t, i_dt_c);
			if ((*it)->getNeighbour(BND_RIGHT) != NULL)
				(*it)->getNeighbour(BND_RIGHT)->synchCopyLayerBeforeRead(LTS, BND_LEFT, l_t, i_dt_c);
		}
		// set ghost layer
		for(vector<SWE_BlockAMR*>::iterator it = l_blocks.begin(); it != l_blocks.end(); ++it) {
			(*it)->setGhostLayerEdge(BND_LEFT);
			(*it)->setGhostLayerEdge(BND_RIGHT);
		}

		// 2. update bottom-top boundary cells
		// update copy layer
		for(vector<SWE_BlockAMR*>::iterator it = l_blocks.begin(); it != l_blocks.end(); ++it) {
			if ((*it)->getNeighbour(BND_BOTTOM) != NULL)
				(*it)->getNeighbour(BND_BOTTOM)->synchCopyLayerBeforeRead(LTS, BND_TOP, l_t, i_dt_c);
			if ((*it)->getNeighbour(BND_TOP) != NULL)
				(*it)->getNeighbour(BND_TOP)->synchCopyLayerBeforeRead(LTS, BND_BOTTOM, l_t, i_dt_c);
		}
		// set ghost layer
		for(vector<SWE_BlockAMR*>::iterator it = l_blocks.begin(); it != l_blocks.end(); ++it) {
			(*it)->setGhostLayerEdge(BND_BOTTOM);
			(*it)->setGhostLayerEdge(BND_TOP);
		}

		// execute Euler time step:
		for(vector<SWE_BlockAMR*>::iterator it = l_blocks.begin(); it != l_blocks.end(); ++it) {
			(*it)->computeNumericalFluxes();
			float l_stepMax = (*it)->getMaxTimestep();
			l_dt = (l_stepMax < l_dt) ? l_stepMax : l_dt;
		}

		if (l_dt > i_dt_c - l_t)
			l_dt = i_dt_c - l_t;

		// update unknowns
		for(vector<SWE_BlockAMR*>::iterator it = l_blocks.begin(); it != l_blocks.end(); ++it) {
			if (interpolationScheme != SPACE) (*it)->synchBeforeRead();
			(*it)->updateUnknowns(l_dt);
			if (interpolationScheme != SPACE) (*it)->synchAfterWrite();
		}

		// simulate blocks on the next refinement level
		if (!i_pq.empty())
			l_dt = simulate_level(l_dt, i_pq.top()->getRefinementLevel(), i_pq);
#ifdef BENCHMARKING
		else {
			time += l_dt;
			priority_queue<SWE_BlockAMR*, vector<SWE_BlockAMR*>, CompareSWE_BlockAMR> l_tmp(blocks);
			while (!l_tmp.empty()) {
				receiver->writeData(time,
									l_dt,
									l_tmp.top()->getOffsetX(),
									l_tmp.top()->getOffsetY(),
									l_tmp.top()->getDx(),
									l_tmp.top()->getDy(),
									l_tmp.top()->getNx(),
									l_tmp.top()->getNy(),
									l_tmp.top()->getNghosts(),
									l_tmp.top()->getWaterHeight(),
									l_tmp.top()->getBathymetry());
				l_tmp.pop();
			}
		}
#endif

		l_t += l_dt;
		l_num_ts++;

		/**
		 * for space interpolation, update the unknowns after calling simulate_level recursively on the next levels of refinement
		 * Reason: the time-step might change (become smaller) after the call, as there might not be enough ghost layers on the fine grids
		 */

		// for all blocks on this refinement level, decrease the computational domain (except for the coarsest grids)
		// stop if the number of time-steps is greater than the refinement level (number of valid ghost cells)
		if (i_level != blocks.top()->getRefinementLevel() && interpolationScheme == SPACE) {
			for(vector<SWE_BlockAMR*>::iterator it = l_blocks.begin(); it != l_blocks.end(); ++it)
				(*it)->decreaseComputationalDomain();
			if (l_num_ts >= i_level)
				break;
		}
	}
	return l_t;
}
Esempio n. 20
0
int main () {
    scanf("%d %d", &n, &m);

    for (int i = 0; i < n; i++) {
        scanf("%lld", &t[i]);
        p[i] = i;
    }
    p[n] = n;

    sort(t, t+n);

    for (int i = 0; i < m; i++) {
        scanf("%lld", &qr[i]);
        p_qr[i] = i;
    }

    sort(p_qr, p_qr+m, cmp_qr);

    int cr = 1;
    st[0] = 0;
    pq.push(pii(-t[0], 0));

    while (!pq.empty()) {
        pii att = pq.top();
        pq.pop();

        st[cr] = -att.first;
        att.first -= t[cr];
        att.second = cr++;
    }

    st[n] = 1e18;
    sort(p, p+n+1, cmp_t);

    curr = 0;
    ll sum = 0;
    for (int _i = 0; _i < m; _i++) {
        int i = p_qr[_i];

        while (curr < n && sum + query(st[p[curr]]) <= qr[i]) {
            sum += query(st[p[curr]]);
            insert();
            tim = st[p[curr]];
            curr++;
        }
        
        ll lo = tim;
        ll hi = st[p[curr]];

        while (lo < hi) {
            ll mid = (lo+hi)/2;
            if (sum + query(mid) >= qr[i])
                hi = mid;
            else
                lo = mid+1;
        }

        res[i] = lo;
    }

    for (int i = 0; i < m; i++) {
        printf("%lld\n", res[i]);
    }
}
Esempio n. 21
0
int main(){
	scanf("%d%d%d%d%d",&n,&m,&r,&S,&T);
	memset(st,-1,sizeof(st));
	for (int i=0;i<m;i++){
		route[i].clear();
		Road[i].clear();
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		id[ln]=i;
		in_edge(u,v,w);
		dest[i]=v;
	}
	for (int i=0;i<r;i++){
		int kn,tp,p;
		for (scanf("%d",&kn),tp=1;tp<=kn;tp++){
			scanf("%d",&p);
			--p;
			if (tp==1) Head[i]=p;
			if (tp==kn) Tail[i]=p;
			Road[p].insert(make_pair(i,route[p].size()));
			route[p].push_back(i);
		}
	}
	for (int i=0;i<m;i++)
		for (int j=0;j<route[id[i]].size();j++) value_path[route[id[i]][j]]+=w[i];
	for (int i=0;i<m;i++) f[i].clear();
	for (int i=0;i<m;i++) g[i].clear();
	while (!Q.empty()) Q.pop();
	for (int i=st[S];i!=-1;i=nxt[i]){
		int k=id[i];
		int mask=0;
		int value=w[i];
		for (int j=0;j<route[k].size();j++){
			if (Head[route[k][j]]==k) mask|=(1<<j);
			if (Tail[route[k][j]]==k && (mask&(1<<j))>0) value+=value_path[route[k][j]];
		}
		f[k].insert(make_pair(mask,value));
		g[k].insert(make_pair(mask,make_pair(-1,-1)));
		Q.push( make_pair( -value, make_pair(k,mask) ) );
	}
	ans=-1;
	while (!Q.empty()){
		int value=-Q.top().first;
		pair<int,int> state=Q.top().second;
		Q.pop();
		int k=state.first,mask=state.second;
		if (value>f[k][mask]) continue;
		int v=dest[k];
		if (v==T){
			if (ans==-1 || value<ans){
				ans=value;
				ansT=k;
				ansMask=mask;
			}
			continue;
		}
		for (int c=st[v];c!=-1;c=nxt[c]){
			int i=id[c];
			int tmask=0;
			int tvalue=value+w[c];
			for (int j=0;j<route[k].size();j++)
				if ((mask&(1<<j))>0){
					if (Road[i].find(route[k][j])!=Road[i].end()) tmask|=(1<<Road[i][route[k][j]]);
				}
			for (int j=0;j<route[i].size();j++){
				if (Head[route[i][j]]==i) tmask|=(1<<j);
				if (Tail[route[i][j]]==i && (tmask&(1<<j))>0) tvalue+=value_path[route[i][j]];
			}
			if (f[i].find(tmask)==f[i].end()){
				f[i].insert(make_pair(tmask,tvalue));
				g[i].insert(make_pair(tmask,make_pair(k,mask)));
				Q.push( make_pair( -tvalue, make_pair( i,tmask ) ) );
			}else
			if (tvalue<f[i][tmask]){
				f[i][tmask]=tvalue;
				g[i][tmask]=make_pair(k,mask);
				Q.push( make_pair( -tvalue, make_pair( i,tmask ) ) );
			}
		}
	}
	printf("%d\n",ans);
	if (ans==-1) return 0;
	path.clear();
	Find(ansT,ansMask);
	printf("%d\n",path.size());
	for (int i=path.size()-1;i>=0;i--) printf("%d ",path[i]+1);puts("");
	return 0;
}
bool mainLoop()
{
    Queue q,q1;

    string new_clause;

    vector<string>::iterator prop,it;

    int i;

    while(!pq.empty())
    {

        q=pq.top();

        pq.pop();

        for(prop=q.propositions.begin();prop!=q.propositions.end();prop++)
        {
            cout<<endl<<"Queue size= "<<pq.size()<<"  Resolve "<<q.i<<" and "<<q.j<<" ";
            new_clause=resolve(clauses[q.i],clauses[q.j],*prop);


            int flag_var=0;

            for(int y=0; y < new_clause.length(); y++)

                if(new_clause[y]!=' ')

                    flag_var=1;

            if(flag_var==0)

            {   t.i=q.i;
                t.j=q.j;
                t.no=trace_no;
                trace_no++;

                trace.push_back(t);


                return true;
            }


            vector<string> tokens;

            //tokenize the string

            tokenizeGeneral(new_clause, tokens);

            //sort it and remove duplicate clauses

            new_clause=sortString(tokens);

            cout<<new_clause<<endl;


            if(!duplicate[new_clause])
            {

                t.i=q.i;
                t.j=q.j;
                t.no=trace_no;
                trace_no++;
                trace.push_back(t);

                clauses.push_back(new_clause);

               //find candidate pairs involving new clause

                for(i=0,it=clauses.begin();it!=clauses.end();it++,i++)
                {
                    vector<string> propositions;

                    int size1, size2;

                    if(isCandidate(new_clause, *it, propositions,size1,size2))
                    {
                        q1.i=i;
                        q1.j=clauses.size()-1;
                        q1.propositions=propositions;
                        q1.size=min(size1,size2);

                        pq.push(q1);
                    }

                }

                duplicate[new_clause]=true;

            }

        }




    }

    return false;

}
Esempio n. 23
0
int dij()
{
	while (!que.empty())
	{
		que.pop();
	}
	acm p, q;
	int i, j, k;
	p.dis = 1;
	for (i = 0; i < n; i++)
	{
		if (t[i].x * t[i].y <= 0)
		{
			dist[i] = 1;
			p.v = i;
			que.push(p);
		}
		else
		{
			dist[i] = INF;
		}
		visit[i] = false;
		path[i] = -1;
	}
	while (!que.empty())
	{
		p = que.top();
		que.pop();
		if (p.dis > dist[p.v] || visit[p.v])
		{
			continue;
		}
		visit[p.v] = true;
		for (i = 0; i < pList[p.v].size(); i++)
		{
			k = pList[p.v][i];
			if (!visit[k] && dist[k] > p.dis + 1)
			{
				dist[k] = p.dis + 1;
				q.dis = dist[k];
				path[k] = p.v;
				q.v = k;
				que.push(q);
			}
		}
	}
	k = INF;
	j = -1;
	for (i = 0; i < n; i++)
	{
		if (t[i].x <= m && m <= t[i].y)
		{
			if (dist[i] < k)
			{
				j = i;
				k = dist[i];
			}
		}
	}
	return j;
}
Esempio n. 24
0
File: vd.cpp Progetto: cerdogan/Job
/* ******************************************************************************************** */
void vd () {

	// Process the site and circle events 
	while(!eventQueue.empty()) {

		// avl.draw();
		getchar2();

		// Check if it is a site event
		Event* event = eventQueue.top();
		eventQueue.pop();
		SiteEvent* siteEvent = dynamic_cast <SiteEvent*> (event);
		if(siteEvent != NULL) {

			printf("\n--- site --------------------------------------------------\n");
			
			// Update the sweep line location
			sweepLine = siteEvent->point(1) - 0.0001;
			printf("sweepLine: %lf\n", sweepLine);
			printf("new site: (%lf, %lf)\n", siteEvent->point(0), siteEvent->point(1));
			//avl.draw();
			getchar2();

			// Locate the existing arc information
			pair <bool, AVL<TreeNode*>::Node*> searchRes = 
				avl.search_candidateLoc(new TreeNode(siteEvent->pi, -1, true));

			// The tree is empty. Temporarily add the site information as a dummy node
			if(searchRes.second == NULL) {
				avl.insert(new TreeNode(siteEvent->pi, -1, true));
				printf("Tree empty!\n");
				continue;
			}

			// The tree still doesn't have a break point, but just a dummy site node information
			TreeNode* parentNode = searchRes.second->value;
			if(parentNode->dummy) {
				avl.remove(parentNode);
				avl.insert(new TreeNode(parentNode->p0i, siteEvent->pi));
				avl.insert(new TreeNode(siteEvent->pi, parentNode->p0i));
				printf("Tree dummy!\n");
				continue;
			}
			
			// Determine the site by comparing it with the found node value
			int prevSiteIdx = 0;
			if(parentNode->value() < siteEvent->point(0)) prevSiteIdx = parentNode->p1i;
			else prevSiteIdx = parentNode->p0i;
			printf("Previous site idx: (%d)\n", prevSiteIdx);
			
			// Create the new break points
			TreeNode* newNode1 = new TreeNode(siteEvent->pi, prevSiteIdx);
			TreeNode* newNode2 = new TreeNode(prevSiteIdx, siteEvent->pi);
 			avl.insert(newNode1);
 			avl.insert(newNode2);

			// Check for "false alarms" for circle events
			set <pair<CircleEvent*, Vector2d>, Vector2dComp>::iterator it =  allCircles.begin();
			printf("# parent circles: %d\n", parentNode->circleEvents.size());
//			for(size_t c_i = 0; c_i < parentNode->circleEvents.size(); c_i++) {
			for(; it != allCircles.end(); it++) {
//				CircleEvent* ce = parentNode->circleEvents[c_i];
				CircleEvent* ce = it->first;
				printf("\tTriplet (%d,%d,%d)\n", ce->points(0), ce->points(1), ce->points(2)); 
				if((ce->center - siteEvent->point).norm() < ce->radius) {
					printf("\tRemoving triplet: (%d,%d,%d)\n", ce->points(0),ce->points(1),ce->points(2));
					ce->falseAlarm = true;
				}
			}
			
			// Get the leaf information to check for circles
			vector <pair<int, AVL<TreeNode*>::Node*> > leafParents;
			avl.traversal_leaves(leafParents);
			printf("Traversal: {");
			vector <pair<int, TreeNode*> > sites;
			for(int i = 0; i < leafParents.size(); i++) {
				TreeNode* node = leafParents[i].second->value;
				int type = leafParents[i].first;
				if(type == 2) {
					printf("(%d,%d), ", node->p0i, node->p1i);
					sites.push_back(make_pair(node->p0i, node));
					sites.push_back(make_pair(node->p1i, node));
				}
				if(type == 0) {
					printf("%d, ", node->p0i);
					sites.push_back(make_pair(node->p0i, node));
				}
				if(type == 1) {
					printf("%d, ", node->p1i);
					sites.push_back(make_pair(node->p1i, node));
				}
			}
			printf("\b\b}\n");

			// Check for circles in triplets
			for(int s_i = 0; s_i < sites.size()-2; s_i++) {

				// Skip newly generated centers
				int i0 = sites[s_i].first, i1 = sites[s_i+1].first, i2 = sites[s_i+2].first;
				if(i0 == i2) continue;

				// If the bottom point of the fit circle can be tangent to the sweep line,
				// add it to the queue
				Vector2d center = fitCircle(data[i0], data[i1], data[i2]);
				double radius = (data[i0]-center).norm();
				double temp_y = center(1) - radius;
				printf("idx: %d, center: (%lf, %lf), temp_y: %lf\n", s_i, center(0), center(1), temp_y);
				printf("radius: %lf, sweepLine: %lf\n", radius, sweepLine);
				if(temp_y < sweepLine) { 

					if (allCircles.find(make_pair((CircleEvent*) NULL, center)) != allCircles.end()) {
						printf("\tTriplet (%d,%d,%d), (%lf, %lf) already exists.\n", i0, i1, i2, center(0), center(1));
						printf("all circles #: %lu\n", allCircles.size());
						continue;
					}

					// Create the circle event
					CircleEvent* ce = new CircleEvent();
					ce->point = Vector2d(center(0), temp_y);
					ce->points = Vector3i(i0,i1,i2);
					ce->center = center;
					ce->radius = radius;
					eventQueue.push(ce);
					allCircles.insert(make_pair(ce, ce->center));
					printf("\tAdding triplet: (%d,%d,%d), (%lf, %lf)\n", i0, i1, i2, center(0), center(1));

					// Register the circle event with the involved arcs
					sites[s_i].second->circleEvents.push_back(ce);
					sites[s_i+1].second->circleEvents.push_back(ce);
					sites[s_i+2].second->circleEvents.push_back(ce);
				}
				else printf("\tCircle already passed, not adding!\n");
			}

		}

		else {

			printf("\n--- circle ------------------------------------------------\n");

			// Update the sweepline
			CircleEvent* ce = dynamic_cast <CircleEvent*> (event);
			printf("circle event: point: (%lf, %lf), center:, (%lf, %lf), points: %d, %d, %d\n", ce->point(0), ce->point(1), ce->center(0), ce->center(1), 
				ce->points(0), ce->points(1), ce->points(2));
			sweepLine = ce->point(1) + 0.00001;
			printf("sweepLine: %lf\n", sweepLine);
			// avl.draw();
			getchar2();

			// Check if false alarm
			if(ce->falseAlarm || ce->falseAlarmCircle) {
				printf("\tFalse alarm!\n");
				continue;
			}

			// Get the arc that is disappearing due to the circle
			pair <bool, AVL<TreeNode*>::Node*> searchRes = 
				avl.search_candidateLoc(new TreeNode(ce->point, Vector2d(), true));
			assert(searchRes.second != NULL && "Could not find the above arc");
			TreeNode* node1 = searchRes.second->value;
			AVL<TreeNode*>::Node* searchNode = searchRes.second;
			printf("node1: (%d,%d)\n", node1->p0i, node1->p1i);

			// Fix node1 if next one is better
			AVL<TreeNode*>::Node* temp = avl.next(searchNode);
			AVL<TreeNode*>::Node* temp2 = avl.prev(searchNode);
			if(temp != NULL) printf("temp: '%s'\n", print(temp->value).c_str());
			if(temp != NULL) printf("temp2: '%s'\n", print(temp2->value).c_str());
			double diff1 = (node1->value() - ce->point(0));
			double diff2 = (temp == NULL) ? 1000.0 : (temp->value->value() - ce->point(0));
			double diff3 = (temp2 == NULL) ? 1000.0 : (temp2->value->value() - ce->point(0));
			printf("\t%lf vs %lf\n", diff1, diff2);
			if(fabs(diff2) < fabs(diff1)) {
				node1 = temp->value;
				searchNode = temp;
				printf("\t\tupdating node1 with temp\n");
			}
			printf("\t%lf vs %lf\n", diff1, diff3);
			if(fabs(diff3) < fabs(diff1)) {
				node1 = temp2->value;
				searchNode = temp2;
				printf("\t\tupdating node1 with temp2\n");
			}
			printf("node1: (%d,%d)\n", node1->p0i, node1->p1i);

			// Skip if the node can't be found
			double diff = (node1->value() - ce->point(0));
			if(fabs(diff) > 0.05) {
				printf("Skipping a circle event (node1) because it is behind the beach line\n");
				continue;
			}

			// Determine the other node
			AVL<TreeNode*>::Node* opt1 = avl.next(searchNode);
			if(opt1 != NULL) printf("opt1: '%s'\n", print(opt1->value).c_str());
			AVL<TreeNode*>::Node* opt2 = avl.prev(searchNode);
			if(opt2 != NULL) printf("opt2: '%s'\n", print(opt2->value).c_str());
			TreeNode* node2;
			if(opt1 == NULL) node2 = opt2->value;
			else if(opt2 == NULL) node2 = opt1->value;
			else {
				double diff1 = (node1->value() - opt1->value->value());	
				double diff2 = (node1->value() - opt2->value->value());	
				printf("diff1: %lf, diff2: %lf\n", diff1, diff2);
				if(fabs(diff1) < fabs(diff2)) node2 = opt1->value;
				else node2 = opt2->value;
			}

			// Skip if the node can't be found
			diff = (node2->value() - ce->point(0));
			if(fabs(diff) > 0.05) {
				printf("Skipping a circle event (node2) because it is behind the beach line\n");
				continue;
			}

			printf("node1: (%d,%d)\n", node1->p0i, node1->p1i);
			printf("node2: (%d,%d)\n", node2->p0i, node2->p1i);

			// Remove any potential circles that were going to use one of the break points for 
			// convergence that just got merged into a voronoi vertex.
			set <pair<CircleEvent*, Vector2d>, Vector2dComp>::iterator it =  allCircles.begin();
			int si0 = ce->points(0), si1 = ce->points(1), si2 = ce->points(2); 
			for(; it != allCircles.end(); it++) {
				CircleEvent* ce = it->first;
				int i0 = ce->points(0), i1 = ce->points(1), i2 = ce->points(2); 
				bool remove = false;
				if((i0 == si0 && i1 == si1) || (i1 == si0 && i2 == si1) || 
					(i0 == si1 && i1 == si0) || (i1 == si1 && i2 == si0)) remove = true; 
				if((i0 == si1 && i1 == si2) || (i1 == si1 && i2 == si2) || 
					(i0 == si2 && i1 == si1) || (i1 == si2 && i2 == si1)) remove = true; 
				
				if(remove) {
					printf("\tRemoving triplet: (%d,%d,%d)\n", i0, i1, i2);
					ce->falseAlarmCircle = true;
				}
			}
	
			// Remove the potential circle events from these nodes
			for(int ce_i = 0; ce_i < node1->circleEvents.size(); ce_i++) {
				CircleEvent* ce = node1->circleEvents[ce_i];
				if(ce->points[0] == node1->p0i && ce->points[1] == node1->p1i)
					ce->falseAlarmCircle = true;
				if(ce->points[1] == node1->p0i && ce->points[2] == node1->p1i)
					ce->falseAlarmCircle = true;
			}
			for(int ce_i = 0; ce_i < node2->circleEvents.size(); ce_i++) {
				CircleEvent* ce = node2->circleEvents[ce_i];
				if(ce->points[0] == node2->p0i && ce->points[1] == node2->p1i)
					ce->falseAlarmCircle = true;
				if(ce->points[1] == node2->p0i && ce->points[2] == node2->p1i)
					ce->falseAlarmCircle = true;
			}

			// Remove the arc from the tree
			printf("Before removes\n");
			getchar2();
			avl.remove(node1);
			// avl.draw();
			printf("Drawn after remove 1\n");
			getchar2();
			avl.remove(node2);
			// avl.draw();
			printf("Drawn after remove 2\n");
			getchar2();

			// Add the new break point 
			TreeNode* newNode;
			if(node1->p0i == node2->p1i)
				newNode = new TreeNode(node2->p0i, node1->p1i);
			else if(node1->p1i == node2->p0i)
				newNode = new TreeNode(node1->p0i, node2->p1i);
			else assert(false && "Unknown new break point creation");
			
 			avl.insert(newNode);
			printf("Inserted new node: '%s'\n", print(newNode).c_str());

			// Set the second points of the completed voronoi edges
			node1->edge1->p1 = ce->center;
			node1->edge2->p0 = ce->center;
			node2->edge1->p1 = ce->center;
			node2->edge2->p0 = ce->center;

			// Find angles around the cell center to place them ccw
			HalfEdge* e1 = node1->edge1, *e2 = node2->edge2;
			int site_idx = (node1->p0i == node2->p1i) ? node1->p0i : node1->p1i;
			Vector2d site = data[site_idx];
			Vector2d v1 = (0.5 * (e1->p0 + e1->p1) - site).normalized();
			Vector2d v2 = (0.5 * (e2->p0 + e2->p1) - site).normalized();
			double angle1 = atan2(v1(1), v1(0)) + (v1(1) < 0 ? 2*M_PI : 0);
			double angle2 = atan2(v2(1), v2(0)) + (v2(1) < 0 ? 2*M_PI : 0);
			if((angle1 < angle2) && fabs(angle1-angle2) > M_PI) angle1 += 2*M_PI;
			else if((angle2 < angle1) && fabs(angle2-angle1) > M_PI) angle2 += 2*M_PI;
			if(angle1 > angle2) {
				e1->prev = e2;
				e2->next = e1;
			}
			else {
				e2->prev = e1;
				e1->next = e2;
			}

			// Get the leaf information to check for circles again
			vector <pair<int, AVL<TreeNode*>::Node*> > leafParents;
			avl.traversal_leaves(leafParents);
			printf("Traversal: {");
			vector <pair<int, TreeNode*> > sites;
			for(int i = 0; i < leafParents.size(); i++) {
				TreeNode* node = leafParents[i].second->value;
				int type = leafParents[i].first;
				if(type == 2) {
					printf("(%d,%d), ", node->p0i, node->p1i);
					sites.push_back(make_pair(node->p0i, node));
					sites.push_back(make_pair(node->p1i, node));
				}
				if(type == 0) {
					printf("%d, ", node->p0i);
					sites.push_back(make_pair(node->p0i, node));
				}
				if(type == 1) {
					printf("%d, ", node->p1i);
					sites.push_back(make_pair(node->p1i, node));
				}
			}
			printf("\b\b}\n");

			// Check for circles in triplets
			for(int s_i = 0; s_i < sites.size()-2; s_i++) {

				// Skip newly generated centers
				int i0 = sites[s_i].first, i1 = sites[s_i+1].first, i2 = sites[s_i+2].first;
				if(i0 == i2) continue;

				// If the bottom point of the fit circle can be tangent to the sweep line,
				// add it to the queue
				Vector2d center = fitCircle(data[i0], data[i1], data[i2]);
				double temp_y = center(1) - (data[i0]-center).norm();
				printf("idx: %d, center: (%lf, %lf), temp_y: %lf\n", s_i, center(0), center(1), temp_y);
				if(temp_y < sweepLine) { 

					// Check if it existed before
					set <pair<CircleEvent*, Vector2d>, Vector2dComp>::iterator it =
						allCircles.find(make_pair((CircleEvent*) NULL, center));
					if(it != allCircles.end() && it->first->falseAlarmCircle){

						printf("\tTurning on an old false alarm for triplet: %d, %d, %d.\n", it->first->points(0), it->first->points(1), it->first->points(2));
						it->first->falseAlarmCircle = false;
						getchar2();
						continue;
					}
					else if(it == allCircles.end()) {

						// Create the circle event
						CircleEvent* ce = new CircleEvent();
						ce->point = Vector2d(center(0), temp_y);
						ce->points = Vector3i(i0,i1,i2);
						ce->center = center;
						eventQueue.push(ce);
						allCircles.insert(make_pair(ce, ce->center));
						printf("\tAdding triplet: (%d, %d, %d)\n", i0, i1, i2);

						// Register the circle event with the involved arcs
						sites[s_i].second->circleEvents.push_back(ce);
						sites[s_i+1].second->circleEvents.push_back(ce);
						sites[s_i+2].second->circleEvents.push_back(ce);
					}
				}

			}

			getchar2();
		}

		
	}
	
}
Esempio n. 25
0
// A Star Algo
//Assuming open_list_member with node_num data member
//Assuming that open_list has start node already pushed into first position in the open list and its g value is set to 0.
void a_star()
{
	//Increase the iteration number
	num_iterations_for_algo++;
	
	//Pop the top of the priority queue
	open_list_member tmp=open_list.top();
	open_list.pop();
	
	cout<<"The node chosen to be expanded from the open list: "<<tmp.node_num<<endl;
	
	//Push all its neighbours into the open list with its g-value and parent appropriately set
	int ngbr_size=nodes[tmp.node_num].neighb_edge_ids.size();
	int i=0,id;
	float w;
	for(i=0;i<ngbr_size;i++)
	{
		//Find the id of the node on the other end of the edge and the weight of the corresponding edge
		id=edges[nodes[tmp.node_num].neighb_edge_ids[i]].find_other_end(tmp.node_num);
		w=edges[nodes[tmp.node_num].neighb_edge_ids[i]].weight;
		
		if(nodes[id].status==1)	//in OL
		{
			if((nodes[id].g_value)>(nodes[tmp.node_num].g_value+w))
			{	
				nodes[id].g_value=nodes[tmp.node_num].g_value+w;
				nodes[id].parent=tmp.node_num;
			}
		}
		else if(nodes[id].status==2)	//in CL (parent redirection)
		{
			if((nodes[id].g_value)>(nodes[tmp.node_num].g_value+w))
			{
				nodes[id].g_value=nodes[tmp.node_num].g_value+w;
				
				if(nodes[id].parent!=tmp.node_num)
					num_parent_pointer_redirections++;
				else
					num_gvalue_update++;
				
				//num_parent_pointer_redirections++;
				nodes[id].parent=tmp.node_num;
			
				//Setting the values of all the children, grand children and so on.
				parent_redirection(id);
			}
		}
		else			// neither in OL nor in CL
		{
			nodes[id].g_value=nodes[tmp.node_num].g_value+w;
			nodes[id].parent=tmp.node_num;
			nodes[id].status=1;
			open_list_member tmp2;
			tmp2.node_num=id;
			open_list.push(tmp2);			
		}
	}
	
	//and push the node expanded in the closed list
	nodes[tmp.node_num].status=2;
	closed_list.push_back(tmp.node_num);
	
	//Test if the top node is the destination, if yes, then terminate the algo else continue.
	if(open_list.empty())
	{
		return;
	}
	else
	{
		tmp=open_list.top();
	
		if(tmp.node_num==goal_node)
		{
			is_reachable=true;
			return;
		}
		a_star();
	}
}
                                                                   /*
###################################################################
## kill_min that receives a priority queue (instead of a vector) ##
###################################################################*/
void kill_min(priority_queue<vertex, vector<vertex>, less<vertex> > max)
{
  vertex leaf, target;
  priority_queue<vertex, vector<vertex>, greater<vertex> > min;
  //printf("____________entering kill_min, filling MIN_priority_queue\n");

  int count = 0;
  // receive max_queue, populate min_queue
	while (!max.empty()) 
  { 
    // put only 'living' vertices into priority_queue -- that are connected
    if (V[max.top().index].dead == 0)
    {
      if (V[max.top().index].incidents == 0)
      {
        //printf("%d has %d incidents\n", max.top().index, V[max.top().index].incidents);
        //printf("putting it into safe vector\n");
        safe.push_back(max.top().index); // save so we can check count when done.
        V[max.top().index].dead = 1;
      }else{
        min.push(max.top());
        count++; 
      }
    }
    max.pop();
  }
  //printf("there are %d in the min_queue now\n", count);

  // if  more to check & is a leaf (or unattached) &  still isn't covered or safe
  while ( !min.empty() && V[min.top().index].incidents < 2)
  {
   if (V[min.top().index].dead != 0)
   {
    min.pop(); // if top of min-Q is already dead, pop it out.
   }
   else
   {
    //printf("min: not empty, top.incidents<2, V[min.top().index].dead != 0\n");

    // catch any new, stray unattached vertices; put them in safe[]
    if (V[min.top().index].incidents == 0)
    {
      //printf("%d has %d incidents\n", min.top().index, V[min.top().index].incidents);
      //printf("putting it into safe vector\n");
      safe.push_back(min.top().index); // save so we can check count when done.
      V[min.top().index].dead = 1;
      min.pop();
    }

    /*###################################
      # This is the real secret to the  #
      # algorithm: any leaf MUST have   #
      # it's "parent" covered.  Working # 
      # from leaves first should help   #
      # achieve a minimum cover.        #
      # THIS IS ENTIRELY THE IDEA OF    #
      # Carlos Brizuela, I'm just implementing it :^D
      ###################################*/   
 
    // remove leaf from future consideration (remove from priority_queue)
    while (V[min.top().index].incidents == 1)
    {
      //printf("vertex %d has %d incident\n", min.top().index, V[min.top().index].incidents);
      // Remove leaf forever from priority_queue, store it in safe vector.
      leaf = min.top();
      V[leaf.index].dead = 1;
      V[leaf.index].incidents--;
      min.pop(); 
      //printf("PUSHED LEAF %d TO safe[], dead = %d, incidents = %d\n", leaf.index, V[leaf.index].dead, V[leaf.index].incidents);
      safe.push_back(leaf.index); // save so we can check count when done.
      
      
      // KILL LEAF'S PARENT:
      // mark leaf's parent as "dead": since we cannot directly access
      // parent in the priority_queue, an alternative is to access it by index
      // in the global V[] array.  There, we can flag it as 'dead'.

      // LEAF could have two edges: the old one, pointing to dead vertex, 
      // and the new one, pointing to the parent we really want to kill.  
      //                                            ^^^^^^
      // TRAVERSE LEAF'S ADJACENCY LIST TO PICK THE LIVING PARENT.
      //                                            ^^^^^^
      edge *current = V[leaf.index].edges;
      while (current != NULL)
      {
        if (V[current->v].dead ==0)
        {
          //printf("Pushing vertex %d (%d's parent) TO covers[]", current->v, leaf.index);
          //printf(", marked it dead.\n");

          V[current->v].dead = 1;
          V[current->v].incidents = 0;// removed, so connected to nothing.
          covers.push_back(V[current->v].index);
          // shouldn't be any other vertices.incidents to decrement

          decrement_incidents(current->v);

          /*###################################################################
            # NOTICE: by removing leaves, then removing their parents, we can
            # create new leaves, but without re-loading non-dead vertices from
            # the global V array (where we are recording .incitents counts), 
            # we are not able to detect newly created leaves here.  So, newly
            # created leaves will have to wait until after we pass through the
            # kill_max() function again.  When kill_max() calls kill_min()
            # it is only at that time that the min_priority-queue is able to 
            # have the leaves created here at the top of the queue. 
            ###################################################################*/
        }
        current = current->next;
      }
      //* BIG INEFFICIENCY FIXED HERE:
      // This clunky block takes into account changes to the global .incidents
      // variables THAT ARE NOT REFLECTED IN THE LOCAL priority_queue.  I'm 
      // basically re-heapifying the priority queue by making it reference
      // the global V array, where actual changes have been made to .incidents.
      vector<int> vee;
      int woof = 0;
      while (min.size() > 0)
      {
        //printf("put %d into vee\n", min.top().index);
        vee.push_back(min.top().index); 
        min.pop();
      } 

      for (int meow = 0; meow < vee.size() ; meow++)
      {
        min.push(V[vee[meow]]);
      }
      //*/
    }
   }
  }
  //printf("No more 0 or 1 incident vertices. Vertex %d has %d incidents\n", min.top().index, V[min.top().index].incidents);


  if (min.size() > 0)
  {
    //printf("Done with min, going to check max_priority_queue again\n");
    kill_max(min);
  }
  //printf("no more to check\n");
}
Esempio n. 27
0
	bool empty () { return que.empty(); };
Esempio n. 28
0
int main(){
#ifndef ONLINE_JUDGE
    freopen("testdata.in", "r", stdin);
#endif
    while (scanf(" %d",&n) != EOF) {
        clr();
        for(int i = 1; i <= n; i++){
            int typ,arg;
            scanf(" %d %d",&typ,&arg);
            if (typ == 1) {
                pque.push(arg);
                que.push(arg);
                stk.push(arg);
            }else{
                if (pque.empty()) {
                    pqf = false;
                }else{
                    if (pque.top() != arg) {
                        pqf = false;
                    }
                    pque.pop();
                }
                
                if (que.empty()) {
                    qf = false;
                }else{
                    if (que.front() != arg) {
                        qf = false;
                    }
                    que.pop();
                }
                
                if (stk.empty()) {
                    sf = false;
                }else{
                    if (stk.top() != arg) {
                        sf = false;
                    }
                    stk.pop();
                }
            }
        }
        
        int cnt = sf + pqf + qf;
        if (cnt > 1) {
            puts("not sure");
        }else if(!cnt){
            puts("impossible");
        }else{
            if (sf) {
                puts("stack");
            }
            if (pqf) {
                puts("priority queue");
            }
            if (qf) {
                puts("queue");
            }
        }
    }
    return 0;
}
Esempio n. 29
0
int main(){
//freopen("in.txt","r",stdin);
freopen("d.in","r",stdin);
freopen("d.out","w",stdout);
	int n;
	cin>>n;



	int ai;
	map<int,int> mp;
	for(int i = 0; i < n; ++i){
		scanf("%d",&ai);
		if(mp.find(ai) == mp.end())
			mp[ai] = 1;
		else
		{
			int t = mp[ai];
			mp[ai] = t+1;
		}
	}


	

	for(map<int,int>::iterator it = mp.begin();it!=mp.end();++it){
		push(it->second,it->first);
	}
/*
	if(odd.size() == 1 && even.size() == 1){
		pii p = even.top();
		int L = p.first/2;
		cout<<L;
		for(int i = 0; i < L; ++i){
			printf("\n%d %d %d %d",p.second,p.second,odd[0].second,odd[0].second);
		}
		return 0;
	}
*/
	

	while(!ones.empty()||!odd.empty()||!even.empty()){
		if(odd.empty() && even.empty())
			fail();

		if(ones.empty() && odd.empty()){
			vector<pii> b;
			Vpii_from_Q(b,even);
			int mx = b.back().second;
			for(int i = 0; i < b.size() -1 ; ++i){
				for(int j = 0 ; j< b[i].second/2; ++j)
					ans_push(b[i].second,b[i].second,mx,mx);
			}
			break;
		}

		if(odd.size() == 1 && ones.empty() && odd.top().first == max_qnt){
			if(!even.empty()){
				vector<pii> b;
				int max_elem = odd.top().second;
				Vpii_from_Q(b,even);
				int mx = b.back().first;
				for(int i = 0; i < b.size(); ++i){
					for(int j = 0 ; j< b[i].second/2; ++j)
						ans_push(b[i].second,b[i].second,max_elem,max_elem);
				}
			}
			break;
		}

		int a,b,c,d;

		pii min_p = minimum();
		pii min_odd = minimum_odd();
		
		a = b = min_p.second;
		c = min_odd.second;





		push(min_p.first - 2,min_p.second);
		push(min_odd.first + 1,min_odd.second);

		min_odd = minimum_odd();
		d = min_odd.second;
		if(min_odd.first == -1)
		{
			vector<pii> b;
			Vpii_from_Q(b,even);
			if(!b.empty()){
				for(int i = 0;i<b.size()-1;++i)
					push(b[i].first,b[i].second);
				push(b.back().first + 1,b.back().second);
				d = b.back().second;
			}
			
		}

		
	
		push(min_odd.first+1,min_odd.second);

		ans_push(a,b,c,d);
		
	}

	int L = ans[0].size();
	cout<<L;
	for(int i = 0; i <L; ++i)
		printf("\n%d %d %d %d",ans[0][i],ans[1][i],ans[2][i],ans[3][i]);
	return 0;

}
void PQPeelTriangles()
{

    TRIANGLEDENSITY= 3.0*NumTriangles/V; 
	TrianglePeelSize=V;
	TrianglePeelSizeFraction=1.0;
	TrianglePeelFe = 2*E/(V*(V-1));
	TrianglePeelTe = 6*NumTriangles/(V*(V-1)*(V-2));
	TrianglePeelEdgeden = 2*E/V;
	
	double numedges=(double)E;
	double numoftriangles=NumTriangles;
	double numvertices=(double)V;	
	
	
	
	for (int i = 1; i <= V; ++i) 
        q.push(make_pair(triangles[i], i));

	int c = q.top().second;
	int counter = 0; 
	while (!q.empty()) 
	{
		int c = q.top().second;
        q.pop();
         if (triangles[c] < 0 )// == -1) 
		{ 
            continue;
        }
		else
		{ 
			TriangleOptVals[counter] = 3.0*numoftriangles/numvertices ;
			permutation[counter++]=c; 
		}
		
        numedges -= degrees[c]; // number of edges goes down by degree of c
        --numvertices; // one vertex less now 
		numoftriangles -= triangles[c];
        triangles[c] = -1; //no need to look at it again 
		if (numvertices > 0) 
		{
			if( TRIANGLEDENSITY <= 3.0*numoftriangles/numvertices  ) 
			{
				TrianglePeelEdgeden = 2.0*numedges/numvertices;
				TRIANGLEDENSITY = 3.0*numoftriangles/numvertices ;
				TrianglePeelSize = numvertices;
				TrianglePeelSizeFraction = numvertices/V;
				TrianglePeelFe = 2*numedges/(numvertices*(numvertices-1));
				TrianglePeelTe = 6*numoftriangles/(numvertices*(numvertices-1)*(numvertices-2));
				OPTIND = counter; 
				//subgraph.clear();
			}
        } 
		for (int i=0; i < AdjList[c].size();i++)
		{
			int w = AdjList[c][i];
			degrees[w]--;
			int Tw = triangles[w];
			if( Tw >= 0 && degrees[c] >=2 ) 
			{
			for(int j = 0; j < AdjList[w].size(); j++)
			{	
  				    int candidate = AdjList[w][j];					
					if( triangles[candidate] > 0 && candidate !=c)
					{
					    
						if( degrees[c] <= degrees[candidate] )
						{
							for (int rc=0; rc < AdjList[c].size(); rc++)
							{
							  if( AdjList[c][rc] == candidate)
									triangles[w]--; 		  								 						
							}
						}
						else
						{
							for (int rc=0; rc < AdjList[candidate].size(); rc++)
								if( AdjList[candidate][rc] == c)									
											triangles[w]--; 		
						}
						
					}				
					
				}
				
				q.push(make_pair(triangles[w], w));				
			}	
			 
		}
		if( counter == V )
		    break;
	}

}