bool isMatch(string s, string p) {
     m.clear();
     int ans = isMatch(s,p,0,0);
     return ans;
 }
 double getExpectedTime(int listSize, int S, int a, int b)
 {
     f.clear();
     return getF(listSize, S, a, b);
 }
Example #3
0
void renderScene(void) {

	//open file
	fstream file;
	stringstream filename;
	filename << "ProjectionData_"<< time(0)<<".dat";

	file.open(filename.str().c_str(),ios::out);


for(int q(100);q>=50;--q)
{
file << "FRAME NO. "<<q<<endl;
for(int fu(0);fu<2;++fu){
	/*if(_m[0]<1)
		_m[0] += 0.1;
	else
		_m[0] = 0.99;*/
/*
	if(_m[4]<1)
		_m[4] += 0.10;
	else
		_m[4] = 0.99;

	if(_m[8]<1)
		_m[8] += 0.10;
	else
		_m[8] = 0.99;*/
	int window_w = 1280;
	int window_h = 1024;

	cout << "render scene... "<<endl;

	TriangleIterator ti;
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glBegin(GL_TRIANGLES);

	//map<int, vector<Pnt3f> > _COLORS;
	map<int, int> _COLORS;

	for(ti = TEST->beginTriangles();ti != TEST->endTriangles();++ti)
	{
		int rgb_index = 0;
		int r(0),g(0),b(0);
		while(_COLORS[rgb_index] != NULL)
		{
			// create random color
			r = (int)rand() % 255;
			g = (int)rand() % 255;
			b = (int)rand() % 255;

			// calculate index
			rgb_index = 256 * g + 256 * 256 * r + b;
			//cout << rgb_index << endl;
		}

		// SAVE ALL _USED_ COLORS
		vector<Pnt3f> v;
		v.push_back(ti.getPosition(0));
		v.push_back(ti.getPosition(1));
		v.push_back(ti.getPosition(2));
		_COLORS[rgb_index] = ti.getIndex();

		//cout << "r " << r << " g "<<g << " b "<<b<<endl;

		// get points from triangle
		Pnt3f p1 = ti.getPosition(0);
		Pnt3f p2 = ti.getPosition(1);
		Pnt3f p3 = ti.getPosition(2);

		//set color and add vertices
		//glColor3f(r,g,b);
		glColor3ub(r,g,b);
		glVertex3f(p1[0],p1[1],p1[2]);
		glVertex3f(p2[0],p2[1],p2[2]);
		glVertex3f(p3[0],p3[1],p3[2]);

	}
	glEnd();

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset(1.0, 1.0);

	glBegin(GL_TRIANGLES);
	// set background color
	glColor3f(0,0,0);
	for(ti = TEST->beginTriangles();ti != TEST->endTriangles();++ti)
	{
		Pnt3f p1 = ti.getPosition(0);
		Pnt3f p2 = ti.getPosition(1);
		Pnt3f p3 = ti.getPosition(2);

		glVertex3f(p1[0],p1[1],p1[2]);
		glVertex3f(p2[0],p2[1],p2[2]);
		glVertex3f(p3[0],p3[1],p3[2]);
	}
	glEnd();

	glDisable(GL_POLYGON_OFFSET_FILL);
	glDisable(GL_DEPTH_TEST);

	//glutSwapBuffers();

	map<int,std::vector<int> > color_map;

	// window size
	int size = window_w*window_h*3;
	// read pixels
	GLubyte *pixels = new GLubyte[size];
	glReadPixels(0 , 0 , window_w , window_h , GL_RGB , GL_UNSIGNED_BYTE , pixels);

	// init RGB and count&debug values
	int red,green,blue;
	int count(0);
	//iterate through pixels
	for(int u(0);u < size;u=u+3){
		// get pixels
		red = pixels[u];
		green = pixels[u+1];
		blue = pixels[u+2];
		// calc unique index
		int index = 256 * green + 256 * 256 * red + blue;
		// ignore black
		if(index == 0 )
			continue;

		// fill RGB vector
		vector<int> ct;
		ct.push_back(red);
		ct.push_back(green);
		ct.push_back(blue);

		// put in map
		color_map[index] = ct;
	}

	cout << "Colors seen in frame: "<< color_map.size()<<endl;

	map<int,vector<int> >::iterator mip;
	// for all _visible_ triangles
	int h(0);
	FaceIterator fit = TEST->beginFaces();
	float thresh = 0.95;
	int count_lines_drawn(0);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINES);

	vector<Pnt3f> cp;
	for(mip = color_map.begin();mip != color_map.end();mip++){
		int face_index = _COLORS[mip->first];
		fit.seek(face_index);

		int a = fit.getPositionIndex(0);
		int b = fit.getPositionIndex(1);
		int c = fit.getPositionIndex(2);

		FaceIterator nit;
		glBegin(GL_LINES);
		glColor3f(1.0,0,0);
		for(nit = TEST->beginFaces();nit != TEST->endFaces();++nit)
		{

			if(fit.getIndex() == nit.getIndex())
				continue;
			int a2 = nit.getPositionIndex(0);
			int b2 = nit.getPositionIndex(1);
			int c2 = nit.getPositionIndex(2);

			// a-b
			if(a == a2 || a == b2 || a == c2)
				if(b == a2 || b == b2 || b == c2){
					if(fit.getNormal(0).dot(nit.getNormal(0)) < thresh){
						count_lines_drawn++;
						//glVertex3f(fit.getPosition(0)[0],fit.getPosition(0)[1],fit.getPosition(0)[2]);
						//glVertex3f(fit.getPosition(1)[0],fit.getPosition(1)[1],fit.getPosition(1)[2]);
						_LINES.push_back(fit.getPosition(0));
						_LINES.push_back(fit.getPosition(1));
						//createControlPoints(_LINES.size()-2,fit.getPosition(0),fit.getPosition(1));
					}
					h++;
				}
			// a-c
			if(a == a2 || a == b2 || a == c2)
				if(c == a2 || c == b2 || c == c2){
					if(fit.getNormal(0).dot(nit.getNormal(0)) < thresh){
						count_lines_drawn++;
						//glVertex3f(fit.getPosition(0)[0],fit.getPosition(0)[1],fit.getPosition(0)[2]);
						//glVertex3f(fit.getPosition(2)[0],fit.getPosition(2)[1],fit.getPosition(2)[2]);
						_LINES.push_back(fit.getPosition(0));
						_LINES.push_back(fit.getPosition(2));
						//createControlPoints(_LINES.size()-2,fit.getPosition(0),fit.getPosition(2));
					}
					h++;
				}
			// c-b
			if(c == a2 || c == b2 || c == c2)
				if(b == a2 || b == b2 || b == c2){
					if(fit.getNormal(0).dot(nit.getNormal(0)) < thresh){
						count_lines_drawn++;
						//glVertex3f(fit.getPosition(1)[0],fit.getPosition(1)[1],fit.getPosition(1)[2]);
						//glVertex3f(fit.getPosition(2)[0],fit.getPosition(2)[1],fit.getPosition(2)[2]);
						_LINES.push_back(fit.getPosition(1));
						_LINES.push_back(fit.getPosition(2));
						//createControlPoints(_LINES.size()-2,fit.getPosition(1),fit.getPosition(2));
					}
					h++;
				}
		}

		glEnd();
	}

	//glutSwapBuffers();

	// DRAW _CONTROLPOINTS_

	//sorted lines by length in _LINES
	//sortLines();
	// create CP's now
	_HITPOINTS.clear();
	_CONTROLPOINTS.clear();
	_CP2D.clear();
	_LINES2D.clear();
	/*for(int i(0);i < _LINES.size()/10;i=i+2){
		createControlPoints(i,_LINES[i],_LINES[i+1]);
	}*/
/*
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glBegin(GL_POINTS);
	glColor3f(0,1,0);

	// for each line
	for(int i(0);i < _CONTROLPOINTS.size(); ++i){
		// get CP-vector
		vector<Pnt3f> cps = _CONTROLPOINTS[i];
		// for every single controlpoint
		for(int j(0);j<cps.size();++j)
			glVertex3f(cps[i][0],cps[i][1],cps[i][2]);
	}
	glEnd();
	glutSwapBuffers();
*/
	cout << "Lines over Threshold :: "<< _CONTROLPOINTS.size() <<endl;
	cout << "Shared Edges :: " << h <<endl;
	cout << "Lines drawn :: " << count_lines_drawn << endl;
	cout << "Lines :: "<< _LINES.size()<<endl;

	//open cv
	stringstream stream;
	stream << "pics/undist/resize/";
	stream << q;
	stream << ".bmp";
	/*"pics/1_1.bmp"*/
	cout << "/*** PICTURE "<< stream.str().c_str() << " ***/"<<endl;

	cv::Mat init_Image2 = cvLoadImage(stream.str().c_str());
	cv::flip(init_Image2,init_Image2,0);

	// overwrite canny with ground truth
	//cv::Mat init_Image2 = cvLoadImage("ground_truth/canny/30c.bmp");

	cv::Mat gray;
	cv::Mat init_Image;// = init_Image2.clone();

	cv::cvtColor(init_Image2,gray,CV_RGB2GRAY);


	cv::Mat gaus;
	cv::GaussianBlur(gray,gaus,cv::Size(3,3),1);
	////cv::Sobel(gray,init_Image,init_Image.type(),1,0,3);
	cv::Canny(gaus,init_Image,5,10,3,true);

	vector<vector<cv::Point> > contours;
	vector<vector<cv::Point> > new_contours;
	cv::findContours(init_Image,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE,cv::Point());

	cv::Mat new_contour = cv::Mat(1024,1280,CV_8UC3);
	// for all contours
	for(int c(0);c<contours.size();++c){
		int size = (contours[c]).size();
		//cout << "size = "<< size <<endl;
		cv::Point start = (contours[c])[0];
		cv::Point end = (contours[c])[size];
		float length = sqrt((start.x-end.x)*(start.x-end.x)+(start.y-end.y)*(start.y-end.y));

		//check contours size
		if(contours[c].size()>20 /* && (size-10 < length < size+10)*/){

			for(int c1(0);c1<contours[c].size();++c1){
				cv::Point tmp = (contours[c])[c1];

				cv::line(new_contour,tmp,tmp,CV_RGB(255,255,255));
			}
		}
		//cout << start.x << " " << start.y<<endl;
		//cout << end.x << " " << end.y<<endl;
		//if(length > 20)
		//cout << "::"<<length<<endl;

	}
	//exit(0);
	cv::Mat cont;
	cv::cvtColor(new_contour,cont,CV_RGB2GRAY);
	init_Image = cont.clone();


	//cv::cvtColor(init_Image,init_Image2,CV_GRAY2RGB);
	//init_Image = init_Image2.clone();

	cv::imshow("gray",init_Image);

	// window size
	size = window_w*window_h*3;
	// read pixels
	GLubyte *pixels2 = new GLubyte[size];
	glReadPixels(0 , 0 , window_w , window_h , GL_RGB , GL_UNSIGNED_BYTE , pixels2);

	cv::Mat ogl = cv::Mat(window_h,window_w,CV_8UC3);
	ogl.data = pixels2;

	cv::flip(ogl,ogl,0);
	//cv::imwrite("test45.bmp",ogl);

	CvSize size2;
	size2.height=1024;
	size2.width=1280;
	cv::Mat result = cv::Mat(size2,CV_8UC3);//= (cv::Mat)cvCreateImage(size2,8,3);

	//MY 2D-POINTS
	GLdouble modelview[16], projection2[16];
	GLint viewport[4];

	glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
	glGetDoublev(GL_PROJECTION_MATRIX, projection2);
	glGetIntegerv(GL_VIEWPORT, viewport);

	/*double tx, ty, tz;
	for(int i(0); i < _LINES.size(); ++i)
	{
		Pnt3f tmp = _LINES[i];
		cout << "3d-point:" << tmp<<endl;
		gluProject(tmp[0], tmp[1], tmp[2],
			modelview, projection2, viewport,
			&tx, &ty, &tz);

		//cout <<"x: " <<tx << "y: "<<ty<<endl;
		Pnt3d res;
		res[0] = tx;
		res[1] = ty;
		res[2] = tz;
		cout <<"2d-point"<<res<<endl;
		_LINES2D.push_back(res);
	}*/

	int thres = (int)_LINES.size();//(int)(_LINES.size()/2)*0.15;
	sortLines3D(thres);
	_HITPOINTS = map<int,vector<Pnt2f> >();
	double tx1, ty1, tz1;
	double tx2, ty2, tz2;
	// draw 2D-Lines
	//define threshold for CP creation

	//cout << ">>>>>> "<<thres<<endl;
	cv::flip(init_Image,init_Image,0);
	int ok(0);
	for(int i(0);i<thres;i=i+2){
		ok = 0;

		// get 3D Line endings
		Pnt3d p1 = _LINES[i];
		Pnt3d p2 = _LINES[i+1];

		if(p1.dist(p2)<0.3){
			continue;
		}

		// get 2d points of line endings
		gluProject(p1[0], p1[1], p1[2],
			modelview, projection2, viewport,
			&tx1, &ty1, &tz1);

		gluProject(p2[0], p2[1], p2[2],
			modelview, projection2, viewport,
			&tx2, &ty2, &tz2);

		// create Normals
		Pnt2f lineStart, lineEnd;
		lineStart[0]=tx1;lineStart[1]=ty1;
		lineEnd[0]=tx2;lineEnd[1]=ty2;
		Pnt2f lineNormal = lineStart - lineEnd;
		float l = sqrt(lineNormal[0]*lineNormal[0]+lineNormal[1]*lineNormal[1]);
		Pnt2f normal1,normal2;
		//normalized Normals 1 & 2
		normal1[0]=-lineNormal[1]/l;normal1[1]=lineNormal[0]/l;
		normal2[0]=lineNormal[1]/l;normal2[1]=-lineNormal[0]/l;

		// draw line
		//cv::line(result,cv::Point(tx1,ty1),cv::Point(tx2,ty2),CV_RGB(255,0,0),1);

		//creating 2d controlpoints
		//float t = createControlPoints2D(i,p1,p2);
		//if(i <= thres){
			//vector<Pnt2d> cp = _CP2D[i];
			vector<Pnt3f> cp = _CONTROLPOINTS[i];
			Pnt2f old_hit = Pnt2f(-1,0);
			for(int j(0);j<cp.size();++j){
				//get single 3D-ControlPoint
				Pnt3d tmp = cp[j];
				//cout <<"i: "<<i<<" j: "<< j<<endl;
				// fixpoint check!
				if(i==0){
					if(_FIX[0] == -1){
						double x,y,z;
						gluProject(tmp[0], tmp[1], tmp[2],
							modelview, projection2, viewport,
							&x,&y,&z);
						//Pnt2d tmp2d;
						_FIX[0] = x;
						_FIX[1] = y;

					//	cout << "::: "<< (_HITPOINTS[0]).size()<<endl;
					}
					(_HITPOINTS[0]).push_back(_FIX);
					cv::circle(result,cv::Point(_FIX[0],_FIX[1]),3,CV_RGB(255,255,0),2);
					continue;
				}

				// project to 2D
				double x,y,z;
				gluProject(tmp[0], tmp[1], tmp[2],
					modelview, projection2, viewport,
					&x,&y,&z);
				Pnt2d tmp2d;
				tmp2d[0] = x;
				tmp2d[1] = y;
				// CONTROLPOINTS DRAWING
				//cv::circle(result,cv::Point(x,y),2,CV_RGB(100,100,100),2);

				//Pnt2f n1 = _NORMALS[i];
				//Pnt2f n2 = _NORMALS[i+1];
				Pnt2f hit = checkNormal(tmp2d,normal1,init_Image);
				Pnt2f hit1 = checkNormal(tmp2d,normal2,init_Image);

				//cout << "hit" << hit <<endl;

				bool outlier = isOutlier(tmp2d, hit,normal1,old_hit);
				bool outlier2= isOutlier(tmp2d,hit1,normal1,old_hit);
				old_hit = hit;

				//drawing
				if(outlier && outlier2){
					//ok++;
					(_HITPOINTS[i]).push_back(Pnt2f(-1,0));
					//cv::circle(result,cv::Point(hit[0],hit[1]),2,CV_RGB(0,255,255),3);
					//cv::circle(result,cv::Point(hit1[0],hit1[1]),2,CV_RGB(0,255,255),3);
					continue;
					}
				else {
					ok++;
					if(!outlier && !outlier2){
						if(tmp2d.dist(hit)<tmp2d.dist(hit1)){
							//cv::line(result,cv::Point(tmp2d[0],tmp2d[1]),cv::Point(hit[0],hit[1]),CV_RGB(0,255,0),1);
							(_HITPOINTS[i]).push_back(hit);
							old_hit = hit;
							//cv::circle(result,cv::Point(hit1[0],hit1[1]),2,CV_RGB(0,255,255),3);
						}
						else{
							//cv::line(result,cv::Point(tmp2d[0],tmp2d[1]),cv::Point(hit1[0],hit1[1]),CV_RGB(0,255,0),1);
							(_HITPOINTS[i]).push_back(hit1);
							old_hit = hit1;
							//cv::circle(result,cv::Point(hit[0],hit[1]),2,CV_RGB(0,255,255),3);
						}
					} else if(!outlier){
						(_HITPOINTS[i]).push_back(hit);
						//cv::line(result,cv::Point(tmp2d[0],tmp2d[1]),cv::Point(hit[0],hit[1]),CV_RGB(0,255,0),1);
						old_hit = hit;
						//cv::circle(result,cv::Point(hit1[0],hit1[1]),2,CV_RGB(0,255,255),3);
						}
						else {
						(_HITPOINTS[i]).push_back(hit1);
						//cv::line(result,cv::Point(tmp2d[0],tmp2d[1]),cv::Point(hit1[0],hit1[1]),CV_RGB(0,255,0),1);
						old_hit = hit1;
						//cv::circle(result,cv::Point(hit[0],hit[1]),2,CV_RGB(0,255,255),3);
						}
					//cv::line(result,cv::Point(tmp2d[0],tmp2d[1]),cv::Point(tmp2d[0]+normal1[0],tmp2d[1]+normal1[1]),CV_RGB(0,255,0));
					//cv::line(result,cv::Point(tmp2d[0],tmp2d[1]),cv::Point(tmp2d[0]+normal2[0],tmp2d[1]+normal2[1]),CV_RGB(0,255,0));
				}

			}

			/*vector<Pnt2f> t_vec = _HITPOINTS[i];
			if(t_vec.size() < 5){
				_CONTROLPOINTS[i].clear();
				_HITPOINTS[i].clear();
			}*/
			cout << i<<"::: "<< (_HITPOINTS[i]).size()<<endl;
			int realHP(0);
			for(int g(0);g<_HITPOINTS[i].size();++g){
				if(_HITPOINTS[i][g] != -1)
					realHP++;
			}
			if((int)_CONTROLPOINTS[i].size()*0.2 > realHP)
			{
				_CONTROLPOINTS[i].clear();
				_HITPOINTS[i].clear();
			}
			//cout << "REAL HITPOINTS IN LINE "<< i << " -> "<<realHP<<endl;
			//cout << ":::"<<ok<<endl;
			// clear if not enough hitpoints on line
			if(ok < 3 && i != 0){
				//(_HITPOINTS[i]).clear();
				//cout << "clear hitlist"<< endl;
			}
	}
	int countCP = 0;
	//int thres = (int)(_LINES.size()/2)*0.15;
	for(int i(0);i<thres;i=i+2){
		//cout << "line : "<<i<<endl;
		vector<Pnt3f> tmp = _CONTROLPOINTS[i];
		vector<Pnt2f> tmp2 = _HITPOINTS[i];
		for(int j(0);j<tmp.size();++j){
			countCP++;
			Pnt2f hitp = tmp2[j];
			//cv::circle(result,cv::Point(hitp[0],hitp[1]),2,CV_RGB(255,255,0));
			//cout << "Point "<< tmp2[j]<<endl;
		//	cout << "3D-Point "<< tmp[j]<<endl;
		}
		//exit(1);
	}
	cout << "####CONTROLPOINTS>> "<< countCP<<endl;
	countCP = 0;

	cout << "#### LEV - MAR ###"<<endl;
	for(int v(0);v<12;++v){
		cout << " " << _m[v];
		if(v%3 == 2)
			cout <<endl;
	}
	cout << "================"<<endl;

	int ret;
	//for(int go(0);go <=25	; ++go)
	ret = dlevmar_dif(mapping,_m,NULL,12,_CP,1000,NULL,NULL,NULL,NULL,NULL);
	//ret = dlevmar_dif(mapping,_m,NULL,12,_CP,1000,NULL,NULL,NULL,NULL,NULL);

	for(int v(0);v<12;++v){
		cout << " " << _m[v];
		//file << " " << projection2[v];
		if(v%3 == 2){
			cout <<endl;
			//file <<endl;
		}
	}
	file << _m[0] << "," << _m[1] << "," << _m[2] << endl;
	file << _m[3] << "," << _m[4] << "," << _m[5] << endl;
	file << _m[6] << "," << _m[7] << "," << _m[8]<< endl;
	file << _m[9] << "," << _m[10] << "," << _m[11]<< endl;
	file << endl;

	cout <<endl;
	cout <<"iterated for: "<<ret<<endl;
	cout << "#### LEV - MAR  - ENDE###"<<endl;
	//cout << "== HIT POINTS USED " << _HITPOINTS.size()<<endl;
	drawModel(result,0,0,255);

	//convert gray canny image back to rgb

	//cv::cvtColor(init_Image,init_Image2,CV_GRAY2RGB);

	// generated error image
	//cv::add(original,result,result);
	cv::flip(init_Image2,init_Image2,0);
	cv::add(init_Image2,result,result);
	// flip like hell
	cv::flip(result,result,0);

	// save image
	cv::imshow("showing image",result);
	stringstream ss;
	ss << time(0) << ".bmp";
	cv::imwrite(ss.str(),result);
	_CONTROLPOINTS.clear();
	_HITPOINTS.clear();
	_LINES.clear();
}
file << "=====" <<endl;
}
file.close();
}
Example #4
0
bool track( std::map< unsigned long long, std::map<int,cv::Point2d> >* p_result, std::map<unsigned long long, std::multimap<int,cv::Point2d> >* p_ext_result, const Mat& occupancy, unsigned long long time_stamp )
{
    static TIME_MICRO_SEC timeTracking; // $BDI@W;~9o(B[usec]
                                 // [timeTracking - commonParam.termTracking, timeTrackig) $B$NHO0O$GDI@W=hM}$r9T$&;v$r0UL#$9$k(B

    static SamplerPosXYTVID sampler; // $BFCD'NL%5%s%W%i(B

    // storageLUM
    // 時刻tk(キー)に対応するLUM集合へのマップ
    // 時刻tkに対応する等速直線運動集合とは、[tk - extractlumParam.term, tk)のPEPMapから作成した等速直線運動集合のことである。
    static LUMStorage storageLUM;

    // tableLUMSlice
    // LUMスライステーブル
    // 時刻tk(キー)におけるLUMスライスの配列へのマップ
    static LUMSliceTable tableLUMSlice;

    // storageTrajectory
    // 作成中の軌跡要素
    static vector<TrajectoryElement> storageTrajectoryElement;

    // resultTrajectory
    // 追跡結果(IDと軌跡のマップ)
    static map<int,CTrajectory> resultTrajectory;

    //static vector<CTrajectory> prevTrajectoriesClustered;
    static map<unsigned long long, std::multimap<int,cv::Point2d> >  remainedExtendedResult;

    // idNext
    // 追跡結果(IDと軌跡のマップ)
    static int idNext;

    static TIME_MICRO_SEC timeEarliestPEPMap;

    static bool flgTrackingStarts;

    static set<TIME_MICRO_SEC> time_of_received_pepmap;

    bool ret = false;

    if( flgFirst ) {
        sampler.clear();
        storageLUM.clear();
        tableLUMSlice.clear();
        storageTrajectoryElement.clear();
        resultTrajectory.clear();
        remainedExtendedResult.clear();
        idNext = 1;
        timeEarliestPEPMap = time_stamp;
        timeTracking = timeEarliestPEPMap + commonParam.termTracking;
        //timeTracking = commonParam.termTracking + 1000000000; // debug code
        flgFirst = false;
        flgTrackingStarts = true;
        logTracking.init( "tracking.log" );
        viewer.SetStartTime( timeEarliestPEPMap );
    }

    // debug code
    //time_stamp = time_stamp - timeEarliestPEPMap + 1000000000;

    if( flgTrackingStarts ) {
        logTracking.set_tracking_block( timeTracking - commonParam.termTracking, timeTracking );
        logTracking.start();
        viewer.SetTrackingStatus( 0 );
        viewer.SetTrackingBlock( timeTracking - commonParam.termTracking, timeTracking );
        flgTrackingStarts = false;
    }
    
    time_of_received_pepmap.insert( time_stamp );

    logTracking.making_trajectory( TrackingProcessLogger::Start );

    // PEPMapをサンプラに追加する
    AddPEPMapToSampler( occupancy
                      , time_stamp
                        , &sampler
                        , extractlumParam.minPEPMapValue
                        , extractlumParam.maxPEPMapValue );

    //
    // LUM抽出
    vector<TIME_MICRO_SEC> addedTime;
    for( TIME_MICRO_SEC tk = timeTracking - commonParam.termTracking; tk <= time_stamp; tk += extractlumParam.interval ) {
        if( storageLUM.find( tk ) == storageLUM.end() ) {
            // 時刻tkのLUMを抽出
            ExtractLUM( &sampler
                        , tk
                        , &storageLUM[ tk ]
                        , &commonParam
                        , &extractlumParam
                        , true );
            addedTime.push_back( tk );

        }
    }

    //
    //  LUMスライステーブル作成
    if( !storageLUM.empty() ) {
        TIME_MICRO_SEC timeLatestLUM = storageLUM.rbegin()->first;
        addedTime.clear();
        // timeLatestLUMまでのLUMが得られているとき,LUMスライステーブルが作成できるのは
        // (timeLatestLUM - extractlumParam.term)まで。この範囲でLUMスライステーブルを作成する。
        for( TIME_MICRO_SEC tk = timeTracking - commonParam.termTracking
            ; tk <= timeLatestLUM - extractlumParam.term
            ; tk += commonParam.intervalTrajectory ) {
            if( tableLUMSlice.find( tk ) == tableLUMSlice.end() ) {
                // 時刻tkのLUMスライス作成
                //cerr << "LUMスライス追加: ";
                MakeLUMSlice( tk, &storageLUM, &tableLUMSlice[ tk ], &extractlumParam );
                addedTime.push_back( tk );
            }
        }
    }

    // tableLUMSliceに追加された各時刻に始点を定める。
    set<PosXYT,PosXYT_XYT_Less> originPos;
    const double intersticeOrigin = 1.0 / sqrt( mktrajectoryParam.densityOrigin ); // $B50@W$N;OE@F1;N$N4V3V(B
    const double rangeOrigin = mktrajectoryParam.distanceImpact * 2.0; // $B50@W$N>pJs(BX,Y$B:BI8$N<~$j(BrangeOrigin$B;MJ}$NHO0O$K;OE@$N8uJd$r:n@.$9$k(B
    int nOrigin = 0;
    for( vector<TIME_MICRO_SEC>::iterator iTk = addedTime.begin(); iTk != addedTime.end(); ++iTk ) {
        TIME_MICRO_SEC tk = *iTk;
        vector<LUMSlice>::iterator itLUMSlice = tableLUMSlice[ tk ].begin();
        for( ; itLUMSlice != tableLUMSlice[ tk ].end(); ++itLUMSlice ) {
            for( double px = itLUMSlice->pos.x - rangeOrigin / 2.0; px < itLUMSlice->pos.x + rangeOrigin / 2.; px += intersticeOrigin ) {
                for( double py = itLUMSlice->pos.y - rangeOrigin / 2.0; py < itLUMSlice->pos.y + rangeOrigin / 2.0; py += intersticeOrigin ) {
                    originPos.insert( PosXYT( (int)( px / intersticeOrigin ) * intersticeOrigin
                                                , (int)( py / intersticeOrigin ) * intersticeOrigin
                                                , tk ) );
                }
            }
        }
        nOrigin = originPos.size();
    }

    // MPIにより始点を各プロセスに割り振る
    // 以下,仮記述
    vector<PosXYT> originPosPerProcess;
    originPosPerProcess.assign( originPos.begin(), originPos.end() );

    //
    // 受け取った始点を基に新たな軌跡を生成する
    int nNewTrj = 0;
    vector<PosXYT>::iterator itOrigin = originPosPerProcess.begin();
    for( int i = 0; itOrigin != originPosPerProcess.end(); ++itOrigin, ++i ) {
        TrajectoryElement trjElement;
        trjElement.insert( *itOrigin );
        storageTrajectoryElement.push_back( trjElement );
        ++nNewTrj;
    }

    //
    // tableLUMSliceに追加された各時刻について軌跡を延長する
    for( vector<TIME_MICRO_SEC>::iterator iTk = addedTime.begin(); iTk != addedTime.end(); ++iTk ) {
        TIME_MICRO_SEC tk = *iTk;
        if( tableLUMSlice.begin()->first != tk ) {
            ExtendTrajectories( tk - commonParam.intervalTrajectory
                                , tk
                                , &storageTrajectoryElement
                                , &tableLUMSlice[ tk - commonParam.intervalTrajectory ]
                                , &commonParam
                                , &mktrajectoryParam );
        }
    }

    logTracking.making_trajectory( TrackingProcessLogger::End );

    if( !tableLUMSlice.empty() && tableLUMSlice.rbegin()->first >= timeTracking ) {
        cout << "Done with making trajectories." << endl;

        if( flgOutputTrackingProcessData2Files ) {
            // Output process infomation of making trajectories.
            double sumValue = std::accumulate( sampler.begin(), sampler.end(), 0.0, PosXYTV_Sum() );
            unsigned int nSample = (unsigned int)( plotParam.kSample /*3.0e-2*//*1.04e-4*/ * sumValue );
            OutputProcess( timeTracking - commonParam.termTracking//tableLUMSlice.begin()->first
                            , timeTracking//tableLUMSlice.rbegin()->first
                            , timeEarliestPEPMap
                            , &sampler
                            , nSample
                            , &storageTrajectoryElement
                            , NULL//pipeGnuplot_Trajectory
                            , extractlumParam.stDeviation
                            , &plotParam );
            cerr << "完了(nSample=" << nSample << ")" << endl;

            // debug code
            if( nSample <= 3 ) {
                cerr << "nSample is no more than 3." << endl;
            }
        }

        //
        // Clustering the trajectories
        //
        logTracking.clustering( TrackingProcessLogger::Start );
        viewer.SetTrackingStatus( 1 );

        cerr << "Calculating a distance table..." << endl;

        //
        // クラスタリングに用いる軌跡(長さがclusterigParam.minLength以上)を取り出す
        vector<TrajectoryElement> trajectoryElementOfMyProc;
        vector<TrajectoryElement>::iterator it = storageTrajectoryElement.begin();
        for( ; it != storageTrajectoryElement.end(); ++it ) {
            if( it->rbegin()->t - it->begin()->t >= clusteringParam.minLength ) {
                trajectoryElementOfMyProc.push_back( *it );
            }
        }

        size_t nAllTrj; // 総軌跡数
        nAllTrj = trajectoryElementOfMyProc.size();
        map<int,CTrajectory> trajectoryForClustering;
        int iTrj = 0;
        for( vector<TrajectoryElement>::iterator it = trajectoryElementOfMyProc.begin(); it != trajectoryElementOfMyProc.end(); ++it ) {
            trajectoryForClustering[ iTrj ].push_back( *it );
            //(*pRecv)[ iTrj ].push_back( *it );
            ++iTrj;
        }


        // 距離テーブルの初期化
        double* distTable = new double[ nAllTrj * nAllTrj ];
        for( size_t i = 0; i < nAllTrj * nAllTrj; ++i ) {
            distTable[ i ] = -2.0;
        }
        CTrajectory_Distance distanceTrajectory( clusteringParam.distanceLimit, clusteringParam.nLimit, clusteringParam.minCommonTimeRange );
        vector<size_t> iTrjToCol( nAllTrj ); // 各プロセスの距離テーブルにおいて列番号と軌跡番号の対応を示したもの
        for( size_t i = 0; i < nAllTrj; ++i ) {
            iTrjToCol[ i ] = i;
        }
        CalculateDistanceTable( distTable
                              , &iTrjToCol
                              , nAllTrj
                              , trajectoryForClustering.begin()
                              , trajectoryForClustering.end()
                              , &trajectoryForClustering
                              , distanceTrajectory );


        // クラスタリング
        vector<CTrajectory> trajectoriesClustered;

        // 初期クラスタの情報を,受信した軌跡一つずつから成るクラスタが生成されるよう準備する。
        vector< vector<int> > indexCluster;
        vector<int> classID( nAllTrj, -1 );
        for( int i = 0; i < (int)nAllTrj; ++i ) {
            indexCluster.push_back( vector<int>( 1, i ) );
        }

        double* dist;

        size_t nCluster;// = indexCluster.size();
        size_t prevNumOfCluster;// = nCluster;
        int cnt_loop = 0;
        do {
            vector< vector<int> > tmpIndexCluster;
            trajectoriesClustered.clear();
            for( vector< vector<int> >::iterator itCluster = indexCluster.begin(); itCluster != indexCluster.end(); ++itCluster ) {
                CTrajectory trj;
                for( vector<int>::iterator itIdxTrj = itCluster->begin(); itIdxTrj != itCluster->end(); ++itIdxTrj ) {
                    map<int,CTrajectory>::iterator itTrj;
                    if( ( itTrj = trajectoryForClustering.find( *itIdxTrj ) ) != trajectoryForClustering.end() ) {
                        trj.insert( trj.end(), itTrj->second.begin(), itTrj->second.end() );
                    } else {
                        cerr << "Trajectory no." << *itIdxTrj << " Not Found(" << nAllTrj << ")." << endl;
                        //exit( 1 );
                    }
                }
                if( !trj.empty() && VerifyClusteredTrajectories( trj, clusteringParam.distVerifyCluster ) ) {
                    trajectoriesClustered.push_back( trj );
                    tmpIndexCluster.push_back( *itCluster );
                }
            }

            // 距離テーブル配置
            nCluster = trajectoriesClustered.size();
            dist = new double[ nCluster * nCluster ];

            //cerr << "再クラスタリング(現在のクラスタ:" << nCluster << "[$B8D(B], $BMxMQ50@W!'(B" << usetrj.size() << "[$BK\(B]$B!K(B...";
            cerr << cnt_loop << "回目...";

            vector<CTrajectory> tmpTrajectoriesClustered( trajectoriesClustered.size() );
            vector<CTrajectory>::iterator itTmpTrj = tmpTrajectoriesClustered.begin();
            for( vector<CTrajectory>::iterator itTrj = trajectoriesClustered.begin(); itTrj != trajectoriesClustered.end(); ++itTrj, ++itTmpTrj ) {
                itTrj->Integrate( &(*itTmpTrj) );
                //cerr << "itTrj->front().size():" << itTrj->front().size() << ", itTmpTrj->front().size():" << itTmpTrj->front().size() << endl;
                //if( itTmpTrj->front().size() == 0 ) {
                //    exit( 1 );
                //}
            }

            for( size_t idx1 = 0; idx1 < tmpTrajectoriesClustered.size(); ++idx1 ) {
                for( size_t idx2 = idx1; idx2 < tmpTrajectoriesClustered.size(); ++idx2 ) {
                    size_t index1 = idx1 * nCluster + idx2;
                    size_t index2 = idx2 * nCluster + idx1;
                    //cerr << "nCluster = " << nCluster << endl;
                    //cerr << "idx1 = " << idx1 << ", $BMWAG?t(B = " << tmpTrajectoriesClustered[ idx1 ].size() << endl;
                    //cerr << "idx2 = " << idx2 << ", $BMWAG?t(B = " << tmpTrajectoriesClustered[ idx2 ].size() << endl;
                    if( false/*cnt_loop == 0*/ ) {
                        // $B:G=i$N%/%i%9%?%j%s%0$N$H$-$O@h$K5a$a$?5wN%%F!<%V%k$r;HMQ$9$k!#(B
                        dist[ index1 ] = dist[ index2 ] = distTable[ idx1 * nAllTrj + idx2 ];
                    } else {
                        dist[ index1 ] = dist[ index2 ] = distanceTrajectory( tmpTrajectoriesClustered[ idx1 ]
                                                                            , tmpTrajectoriesClustered[ idx2 ] );
                    }
                    //TrajectoryElement_Distance distanceTrajectoryElement( clusteringParam.distanceLimit, clusteringParam.nLimit, clusteringParam.minCommonTimeRange );
                    //cerr << "idx1:" << tmpTrajectoriesClustered[ idx1 ].front().size() << ", idx2:" << tmpTrajectoriesClustered[ idx2 ].front().size() << ", ";
                    //cerr << "$B5wN%(B = ";
                    //dist[ index1 ] = dist[ index2 ] = distanceTrajectoryElement( tmpTrajectoriesClustered[ idx1 ].front()
                    //                                                           , tmpTrajectoriesClustered[ idx2 ].front() );
                    //cerr << dist[ index1 ] << endl;
                }
            }

#if 1

            // クラスタを間引く
            cerr << "利用クラスタの選定...";
            vector<int> idxClusterUse;
            if( !tmpTrajectoriesClustered.empty() ) {
                vector<double> frequency( tmpTrajectoriesClustered.size(), 0.0 );
                CalcFrequency( (double*)&(frequency[ 0 ]), dist, tmpTrajectoriesClustered.size(), 0.1, clusteringParam.thDistance );
                ReduceTrajectory( &idxClusterUse, (double*)&(frequency[0]), frequency.size(), 55.0/*80.0*/ );
            }
            cerr << "完了(" << idxClusterUse.size() << "[個])...";

            // 距離テーブル再配置
            double* dist2 = new double[ idxClusterUse.size() * idxClusterUse.size() ];
            for( vector<int>::iterator itIdxCluster = idxClusterUse.begin(); itIdxCluster != idxClusterUse.end(); ++itIdxCluster ) {
                for( vector<int>::iterator it = idxClusterUse.begin(); it != idxClusterUse.end(); ++it ) {
                    size_t idxDst = distance( idxClusterUse.begin(), itIdxCluster ) * idxClusterUse.size()
                                    + distance( idxClusterUse.begin(), it );
                    size_t idxSrc = *itIdxCluster * nCluster + *it;
                    dist2[ idxDst ] = dist[ idxSrc ];
                }
            }

            vector<int> classID( idxClusterUse.size(), -1 );
            Clustering( &classID, dist2, idxClusterUse.size(), clusteringParam.distVerifyCluster );

            vector< vector<int> > tmp;
            Clustering2( &tmp, classID, dist2, idxClusterUse.size(), clusteringParam.thConnect, clusteringParam.thDistance );

            delete [] dist2;


            indexCluster.clear();
            for( vector< vector<int> >::iterator itClusterIdx = tmp.begin(); itClusterIdx != tmp.end(); ++itClusterIdx ) {
                vector<int> clusterIdx;
                for( vector<int>::iterator it = itClusterIdx->begin(); it != itClusterIdx->end(); ++it ) {
                    clusterIdx.insert( clusterIdx.end()
                                        , tmpIndexCluster[ idxClusterUse[ *it ] ].begin()
                                        , tmpIndexCluster[ idxClusterUse[ *it ] ].end() );
                }
                sort( clusterIdx.begin(), clusterIdx.end() );
                clusterIdx.erase( unique( clusterIdx.begin(), clusterIdx.end() ), clusterIdx.end() );
                indexCluster.push_back( clusterIdx );
            }

            prevNumOfCluster = nCluster;//idxClusterUse.size();// nCluster;
            nCluster = indexCluster.size();
            cerr << "終了(クラスタ:" << nCluster << "[個], trajectoriesClustered.size()=" << trajectoriesClustered.size() << ")";
            cerr << endl;

            //
            // Output process information of clustering
            if( flgOutputTrackingProcessData2Files ) {
                ++cnt_loop;
                if( trajectoriesClustered.size() < 30 ) {
                    ostringstream oss;
                    oss << cnt_loop;
                    double sumValue = accumulate( sampler.begin(), sampler.end(), 0.0, PosXYTV_Sum() );
                    unsigned int nSample = (unsigned int)( plotParam.kSample /*3.0e-2*//*1.04e-4*/ * sumValue );
                    OutputProcess( timeTracking - commonParam.termTracking//tableLUMSlice.begin()->first
                                    , timeTracking//tableLUMSlice.rbegin()->first
                                    , timeEarliestPEPMap
                                    , &sampler
                                    , nSample
                                    , &trajectoriesClustered
#ifdef WINDOWS_OS
			            , "C:\\Users\\fukushi\\Documents\\project\\HumanTracking\\bin\\tmp_trajectories\\"
#endif
#ifdef LINUX_OS
			            , "/home/kumalab/project/HumanTracking/bin/tmp_trajectories/"
#endif
                                    , oss.str()
                                    , NULL
                                    , &plotParam );
                }
                
            }
#endif
            delete [] dist;
        } while( prevNumOfCluster != nCluster );

        logTracking.clustering( TrackingProcessLogger::End );

        logTracking.renovation( TrackingProcessLogger::Start );
        viewer.SetTrackingStatus( 2 );

        //
        // Renovate the trajectories
        TrajectoriesInfo infoTrj;
        infoTrj.section.resize( 1 );

        cerr << "Started renovation: [ " << timeTracking - commonParam.termTracking - timeEarliestPEPMap
                << ", " <<  timeTracking - timeEarliestPEPMap << " )" << endl;

        // クラスタリングした軌跡を平均してinfoTrjに格納する
        infoTrj.trjElement.resize( trajectoriesClustered.size() );
        for( int i = 0; i < (int)trajectoriesClustered.size(); ++i ) {
            CTrajectory trj;
            trajectoriesClustered[ i ].Integrate( &trj );
            infoTrj.trjElement[ i ] = trj.front();
        }

//        if( myRank == 0 ) {
//            cout << " クラスタリングした軌跡を追加: 総計" << infoTrj.trjElement.size() << "[個]" << endl;
//        }

        // 前回の追跡結果(resultTrajectory)を[ timeTracking - commonParam.termTracking, timeTracking )で
        // クリップしてinfoTrjに格納する
        int idx = (int)trajectoriesClustered.size();
        map<int,int> reserve; // 軌跡番号と既存のIDの組み合わせ
        for( map<int,CTrajectory>::iterator itResult = resultTrajectory.begin(); itResult != resultTrajectory.end(); ++itResult ) {
            CTrajectory trj;
            trj = itResult->second;
            trj.Clip( timeTracking - commonParam.termTracking, timeTracking );
            if( !trj.empty() ) {
                infoTrj.trjElement.push_back( trj.front() );
                reserve[ idx ] = itResult->first;
                ++idx;
            }
        }

//        if( myRank == 0 ) {
//            cout << " 前回の追跡結果を追加: 総計" << infoTrj.trjElement.size() << "[個]" << endl;
//        }

        //
        // 軌跡の出力
//            if( myRank == 0 ) {
//                vector<CTrajectory> vectrj;
//                for( vector<TrajectoryElement>::iterator it = infoTrj.trjElement.begin(); it != infoTrj.trjElement.end(); ++it ) {
//                    CTrajectory trj;
//                    trj.push_back( *it );
//                    vectrj.push_back( trj );
//                }
//                double sumValue = accumulate( sampler.begin(), sampler.end(), 0.0, PosXYTV_Sum() );
//                unsigned int nSample = (unsigned int)( 1.04e-4 * sumValue );
//                OutputProcess( timeTracking - commonParam.termTracking//tableLUMSlice.begin()->first
//                             , timeTracking//tableLUMSlice.rbegin()->first
//                             , timeEarliestPEPMap
//                             , &sampler
//                             , nSample
//                             , &vectrj
//                             , "./tmp_preoptimize/"
//                             , ""
//                             , NULL
//                             , &plotParam );
//            }

        // セクション分割
        map<int,int> pointIdxToTrjNo;
        DivideIntoSections( &infoTrj, &pointIdxToTrjNo, rnvtrjParam );

        // 各セクションでセットを作成
        for( int i = 0; i < (int)infoTrj.section.size(); ++i ) {
            MakeSet( i, &infoTrj, &reserve );
//            cout << "  セクション" << i << ": " << infoTrj.section[ i ].trjSet.size() << "[個]" << endl;
        }

//        start_d = MPI_Wtime();
//        cout << "Optimize()...";
        // 最適解の探索
        vector<TrajectoryElement> opt;
        vector<int> idOpt;
        double min = -1.0;
        //if( myRank == 0 ) {
        cerr << "  Optimum analysis: # of sections" << (int)infoTrj.section.size() << endl;
        //}
        for( int idxSec = 0; idxSec < (int)infoTrj.section.size(); ++idxSec ) {
            min = -1.0;
            int idxMinSet = -1;
            vector<TrajectoryElement> optOfSec;
            vector<int> idOptOfSec;
            for( int idxSet = 0; idxSet < (int)infoTrj.section[ idxSec ].trjSet.size(); ++idxSet ) {
                vector<TrajectoryElement> trjElement;
                vector<int> idTrjElement;
                double t1 = 0.0, t2 = 0.0, t3 = 0.0;
                double e = Optimize( &trjElement, &idTrjElement, &reserve, idxSec, idxSet, 20, &infoTrj, &pointIdxToTrjNo, rnvtrjParam, &t1, &t2, &t3 );
                if( e >= 0.0 && ( min < 0.0 || e < min ) ) {
                    optOfSec = trjElement;
                    idOptOfSec = idTrjElement;
                    idxMinSet = idxSet;
                    min = e;
                }
            }
            cerr << " Optimization result: Set" << idxMinSet << endl;
            cerr << "    # of trajectories " << optOfSec.size() << endl;

            opt.insert( opt.end(), optOfSec.begin(), optOfSec.end() );
            idOpt.insert( idOpt.end(), idOptOfSec.begin(), idOptOfSec.end() );
        }

//#define RE_RENOVATE
#ifdef RE_RENOVATE
        //
        // $B:F=$I|$r9T$&(B
        //if( myRank == 0 ) {
            cerr << "  Re-renovation";
        //}

        // $B5a$a$?:GE,2r$r%;%C%H(B
        infoTrj.trjElement = opt;

        // $BM=Ls50@W$r5a$a$k(B
        reserve.clear();
        for( int idx = 0; idx < (int)idOpt.size(); ++idx ) {
            if( idOpt[ idx ] != -1 ) {
                reserve[ idx ] = idOpt[ idx ];
            }
        }

        // $B%;%/%7%g%sJ,3d(B
        DivideIntoSections( &infoTrj, rnvtrjParam );

        // $B3F%;%/%7%g%s$G%;%C%H$r:n@.(B
        for( int i = 0; i < (int)infoTrj.section.size(); ++i ) {
            MakeSet( i, &infoTrj, &reserve );
        }

        // $B:GE,2r$NC5:w(B
        opt.clear();
        idOpt.clear();
        min = -1.0;
        for( int idxSec = 0; idxSec < (int)infoTrj.section.size(); ++idxSec ) {
            min = -1.0;
            int idxMinSet = -1;
            vector<TrajectoryElement> optOfSec;
            vector<int> idOptOfSec;
            for( int idxSet = 0; idxSet < (int)infoTrj.section[ idxSec ].trjSet.size(); ++idxSet ) {
                vector<TrajectoryElement> trjElement;
                vector<int> idTrjElement;
                double t1 = 0.0, t2 = 0.0, t3 = 0.0;
                double e = Optimize( &trjElement, &idTrjElement, &reserve, idxSec, idxSet, 100/*20*/, &infoTrj, rnvtrjParam, &t1, &t2, &t3 );
                if( e >= 0.0 && ( min < 0.0 || e < min ) ) {
                    optOfSec = trjElement;
                    idOptOfSec = idTrjElement;
                    idxMinSet = idxSet;
                    min = e;
                }
            }

            opt.insert( opt.end(), optOfSec.begin(), optOfSec.end() );
            idOpt.insert( idOpt.end(), idOptOfSec.begin(), idOptOfSec.end() );
        }

        //if( myRank == 0 ) {
            cerr << "  Done..." << endl;
        //}
#endif

	    logTracking.renovation( TrackingProcessLogger::End );
        viewer.SetTrackingStatus( 3 );

        logTracking.finishing( TrackingProcessLogger::Start );

        // ID未割り当ての軌跡に新しいIDを振る
        for( vector<int>::iterator itID = idOpt.begin(); itID != idOpt.end(); ++itID ) {
            if( *itID == -1 ) {
                *itID = idNext;
                ++idNext;
            }
        }

        // 軌跡の補間を行う
        for( vector<TrajectoryElement>::iterator itTrj = opt.begin(); itTrj != opt.end(); ++itTrj ) {
            TrajectoryElement::iterator it = itTrj->begin();
            TrajectoryElement::iterator itNext = it;
            advance( itNext, 1 );
            while( itNext != itTrj->end() ) {
                while( it->t + commonParam.intervalTrajectory < itNext->t ) {
                    PosXYT pos;
                    pos.x = ( itNext->x - it->x ) / ( (double)( itNext->t - it->t ) * 1.0e-6 ) * ( (double)commonParam.intervalTrajectory * 1.0e-6 ) + it->x;
                    pos.y = ( itNext->y - it->y ) / ( (double)( itNext->t - it->t ) * 1.0e-6 ) * ( (double)commonParam.intervalTrajectory * 1.0e-6 ) + it->y;
                    pos.t = it->t + commonParam.intervalTrajectory;
                    it = itTrj->insert( it, pos );
                }
                ++it;
                ++itNext;
            }
        }

        // 結果の保存
        p_result->clear();
        resultTrajectory.clear();
        vector<int>::iterator itID = idOpt.begin();
        for( vector<TrajectoryElement>::iterator itTrj = opt.begin(); itTrj != opt.end(); ++itTrj, ++itID ) {
            int id = ( *itID == -1 ) ? idNext++ : *itID;
            CTrajectory trj;
            trj.push_back( *itTrj );
            resultTrajectory[ id ] = trj; // resultTrajectory$B$O<!2s$NDI@W$K$b;H$&$N$G>/$7D9$$(B
            //trj.Clip( 0, timeTracking - ( commonParam.termTracking - commonParam.intervalTracking ) );
            //(*p_result)[ id ] = trj; // $BI=<(MQ(B
        }

        //map<unsigned long long, multimap<int,Point2d> > ext_result;

        unsigned long long time;
        p_ext_result->insert( remainedExtendedResult.begin(), remainedExtendedResult.end() );
        for( /*unsigned long long*/ time = max( timeTracking - commonParam.termTracking, timeEarliestPEPMap )
                ; time < timeTracking - ( commonParam.termTracking - commonParam.intervalTracking )
                ; time += commonParam.intervalTrajectory ) {

            (*p_result)[ time ];
            (*p_ext_result)[ time ];

            const set<TIME_MICRO_SEC>::iterator it_start_pepmap_time = time_of_received_pepmap.lower_bound( time );
            const set<TIME_MICRO_SEC>::iterator it_end_pepmap_time = time_of_received_pepmap.lower_bound( time + commonParam.intervalTrajectory );
            for( set<TIME_MICRO_SEC>::iterator it = it_start_pepmap_time; it != it_end_pepmap_time; ++it ) {
               (*p_ext_result)[ *it ]; 
            }

            map<int,CTrajectory>::const_iterator itResult = resultTrajectory.begin();
            for( ; itResult != resultTrajectory.end(); ++itResult ) {
                const CTrajectory& trajectory = itResult->second;
                if( trajectory.size() > 0 ) {
                    TrajectoryElement::iterator itPos = trajectory.front().begin();
                    for( ; itPos != trajectory.front().end(); ++itPos ) {
                        if( itPos->t == time ) {
                            (*p_result)[ time ][ itResult->first ] = Point2d( itPos->x, itPos->y );

                            const int trj_no = itPos->ID;
                            if( trj_no < trajectoriesClustered.size() ) {
                                for( CTrajectory::iterator it = trajectoriesClustered[ trj_no ].begin()
                                   ; it != trajectoriesClustered[ trj_no ].end(); ++it ) {
                                    TrajectoryElement::iterator itPos2;
                                    if( ( itPos2 = it->find( PosXYT( 0.0, 0.0, time ) ) ) != it->end() ) {
                                        (*p_ext_result)[ time ].insert( pair<int,Point2d>( itResult->first, Point2d( itPos2->x, itPos2->y ) ) );
                                        PosXYT pos0, pos1;
                                        pos0 = *itPos2;
                                        advance( itPos2, 1 );
                                        if( itPos2 != it->end() ) {
                                            pos1 = *itPos2;
                                            for( set<TIME_MICRO_SEC>::iterator it = it_start_pepmap_time; it != it_end_pepmap_time; ++it ) {
                                                PosXYT pos;
                                                pos.x = ( pos1.x - pos0.x ) / ( (double)( pos1.t - pos0.t ) ) * ( (double)( *it - *it_start_pepmap_time ) ) + pos0.x;
                                                pos.y = ( pos1.y - pos0.y ) / ( (double)( pos1.t - pos0.t ) ) * ( (double)( *it - *it_start_pepmap_time ) ) + pos0.y;
                                                (*p_ext_result)[ *it ].insert( pair<int,Point2d>( itResult->first, Point2d( pos.x, pos.y ) ) );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        remainedExtendedResult.clear();
        for( ; time < timeTracking; time += commonParam.intervalTrajectory ) {
            const set<TIME_MICRO_SEC>::iterator it_start_pepmap_time = time_of_received_pepmap.lower_bound( time );
            const set<TIME_MICRO_SEC>::iterator it_end_pepmap_time = time_of_received_pepmap.lower_bound( time + commonParam.intervalTrajectory );

            map<int,CTrajectory>::const_iterator itResult = resultTrajectory.begin();
            for( ; itResult != resultTrajectory.end(); ++itResult ) {
                const CTrajectory& trajectory = itResult->second;
                if( trajectory.size() > 0 ) {
                    TrajectoryElement::iterator itPos = trajectory.front().begin();
                    for( ; itPos != trajectory.front().end(); ++itPos ) {
                        if( itPos->t == time ) {
                            //(*p_result)[ time ][ itResult->first ] = Point2d( itPos->x, itPos->y );

                            const int trj_no = itPos->ID;
                            //if( trj_no < trajectoriesClustered.size() ) {
                                for( CTrajectory::iterator it = trajectoriesClustered[ trj_no ].begin()
                                   ; it != trajectoriesClustered[ trj_no ].end(); ++it ) {
                                    TrajectoryElement::iterator itPos2;
                                    if( ( itPos2 = it->find( PosXYT( 0.0, 0.0, time ) ) ) != it->end() ) {
                                        (*p_ext_result)[ time ].insert( pair<int,Point2d>( itResult->first, Point2d( itPos2->x, itPos2->y ) ) );
                                        PosXYT pos0, pos1;
                                        pos0 = *itPos2;
                                        advance( itPos2, 1 );
                                        if( itPos2 != it->end() ) {
                                            pos1 = *itPos2;
                                            for( set<TIME_MICRO_SEC>::iterator it = it_start_pepmap_time; it != it_end_pepmap_time; ++it ) {
                                                PosXYT pos;
                                                pos.x = ( pos1.x - pos0.x ) / ( (double)( pos1.t - pos0.t ) ) * ( (double)( *it - *it_start_pepmap_time ) ) + pos0.x;
                                                pos.y = ( pos1.y - pos0.y ) / ( (double)( pos1.t - pos0.t ) ) * ( (double)( *it - *it_start_pepmap_time ) ) + pos0.y;
                                                remainedExtendedResult[ *it ].insert( pair<int,Point2d>( itResult->first, Point2d( pos.x, pos.y ) ) );
                                            }
                                        }
                                    }
                                }
                            //}
                        }
                    }
                }
            }       
        }


        viewer.SetResult( *p_result );

        //
        // Output process information of renovation
        //if( myRank == 0 ) {
        if( flgOutputTrackingProcessData2Files ) {
            {
                double sumValue = accumulate( sampler.begin(), sampler.end(), 0.0, PosXYTV_Sum() );
                unsigned int nSample = (unsigned int)( plotParam.kSample /*3.0e-2*//*1.04e-4*/ * sumValue );
                OutputProcess( timeTracking - commonParam.termTracking//tableLUMSlice.begin()->first
                             , timeTracking//tableLUMSlice.rbegin()->first
                             , timeEarliestPEPMap
                             , &sampler
                             , nSample
                             , &resultTrajectory
                             , NULL
                             , &plotParam );
            }
        }

        delete [] distTable;

        //
        // sampler
        sampler.erase( sampler.begin()
                        , lower_bound( sampler.begin()
                                    , sampler.end()
                                    , pair<PosXYT,unsigned long>( PosXYT( 0.0, 0.0, timeTracking - ( commonParam.termTracking - commonParam.intervalTracking ) ), 0 )
                                    , PosXYT_T_Less() ) );

        //
        // storageLUM
        storageLUM.erase( storageLUM.begin()
                        , storageLUM.lower_bound( timeTracking - ( commonParam.termTracking - commonParam.intervalTracking ) ) );

        //
        // tableLUMSlice
        tableLUMSlice.erase( tableLUMSlice.begin()
                            , tableLUMSlice.lower_bound( timeTracking - ( commonParam.termTracking - commonParam.intervalTracking ) ) );


        //
        // storageTrajectoryElement
        // [timeTracking - commonParam.termTracking, timeTracking]$B$K%/%j%C%T%s%0(B
        CTrajectory newStorageTrajectoryElement;
        newStorageTrajectoryElement.assign( storageTrajectoryElement.begin(), storageTrajectoryElement.end() );
        newStorageTrajectoryElement.Clip( timeTracking - ( commonParam.termTracking - commonParam.intervalTracking ), timeTracking );
        storageTrajectoryElement.assign( newStorageTrajectoryElement.begin(), newStorageTrajectoryElement.end() );

        time_of_received_pepmap.erase( time_of_received_pepmap.begin()
                                     , time_of_received_pepmap.lower_bound( timeTracking - ( commonParam.termTracking - commonParam.intervalTracking ) ) );


        //prevTrajectoriesClustered = trajectoriesClustered;


        timeTracking += commonParam.intervalTracking;

        ret = true;

        logTracking.finishing( TrackingProcessLogger::End );

        logTracking.end_and_output2file();
        flgTrackingStarts = true;
    }

    return ret;
}
Example #5
0
int main() {
	int test_case;
	int first = 1;
	scanf("%d", &test_case);
	while (test_case--) {
		if (!first) {
			printf("\n");
		}
		memset(head, -1, sizeof(head));
		memset(value, 0, sizeof(value));
		maps.clear();
		edge_number = 0;
		cnt = 1;
		source = 0;
		plug.clear();
		int plug_number, device, adapter;
		scanf("%d", &plug_number);
		int temp = plug_number;
		for (int i = 1; i <= plug_number; i++) {
			string name;
			cin >> name;
			plug.push_back(cnt);
			if (maps[name]) {
				value[maps[name]]++;
				temp--;
			}
			else {
				value[cnt] = 1;
				maps[name] = cnt++;
			}
		}
		scanf("%d", &device);
		for (int i = 1; i <= device; i++) {
			string device_name, plug;
			cin >> device_name >> plug;
			int id_1 = maps[plug];
			int id_2 = cnt;
			maps[device_name] = cnt++;
			addEdge(source, id_2, 1, 0);
			addEdge(id_2, id_1, 1, 0);
		}
		scanf("%d", &adapter);
		for (int i = 1; i <= adapter; i++) {
			string name_1, name_2;
			cin >> name_1 >> name_2;
			if (!maps[name_1]) {
				plug.push_back(cnt);
				maps[name_1] = cnt++;
			}
			if (!maps[name_2]) {
				plug.push_back(cnt);
				maps[name_2] = cnt++;
			}
			int id_1 = maps[name_1];
			int id_2 = maps[name_2];
			addEdge(id_1, id_2, INF, 0);
		}
		destination = cnt++;
		for (int i = 0; i < plug.size(); i++) {
			addEdge(plug[i], destination, value[plug[i]], 0);
		}
		int ans;
		ans = dinic();
		printf("%d\n", device - ans);
		first = 0;
	}
	return 0;
}
Example #6
0
File: A.cpp Project: chyyuu/ACM
int main()
{

    int n,m,nm,r,s,tmp,q,i,j;
    char _string_tmp[40];
    int cas,ans;
    scanf("%d",&cas);
    memset(a,0,sizeof(a));
    for(i=2; i<=10000; i++)
    {
        if(a[i]==0)
        {
            isprime[i]=1;
            for(j=i+i; j<=10000; j+=i)
                a[j]=1;
        }
    }
    while(cas--)
    {
        memset(pro_first,false,sizeof(pro_first));
        memset(pro_second,false,sizeof(pro_second));
        scanf("%d%d",&n,&m);
        scanf("%d",&r);

        while(r--)
        {
            scanf("%d",&tmp);
            pro_first[tmp] = true;
        }
        scanf("%d",&s);

        while(s--)
        {
            scanf("%d",&tmp);
            pro_second[tmp] = true;
        }
        Map.clear();
        scanf("%d",&q);
        while(q--)
        {
            scanf("%s%d",_string_tmp,&tmp);
            Map[_string_tmp] = tmp;
        }
        for(i=0; i<n; i++)
        {
            info[i].score=0;
            scanf("%s%s%s",info[i].name,info[i].team,info[i].sex);
            for(j=0;info[i].name[j];j++){
                if(info[i].name[j] >='A' && info[i].name[j]<='Z'){
                    info[i]._name[j] = info[i].name[j] - 'A' + 'a';
                }else{
                    info[i]._name[j] = info[i].name[j];
                }
            }

            if(info[i].sex[0]=='F')info[i].score+=33;

            tmp =Map[info[i].team] ;
            info[i].score+=getscore(tmp);

            scanf("%d",&info[i].pro_num);
            scanf("%d",&info[i].contest_num);
            //cout<< info[i].score <<" #$#### "<<endl;
            while(info[i].pro_num--)
            {
                scanf("%d",&tmp);
                double scores=0;
                bool ok = false;
                if(pro_first[tmp])
                {
                    info[i].score+=2.5,scores = 2.5;
                    ok = true;
                }

                else if(pro_second[tmp])
                {
                    info[i].score+=1.5,scores = 1.5;
                     ok = true;
                }

                else if(isprime[tmp])
                {
                    info[i].score+=1.0,scores = 1.0;
                     ok = true;
                }

                else if(!ok){
                    info[i].score+=0.3,scores = 0.3;
                }
            }
            for(j=0; j<info[i].contest_num; j++)
            {
                scanf("%lf",&info[i].contest_str[j]);
            }
            // cout<<i<< " $$$$$$$$$$$ "<<info[i].score<<endl;
            if(info[i].contest_num>=3)
            {
                sort(info[i].contest_str,info[i].contest_str+info[i].contest_num);
                double dtmp = info[i].contest_str[info[i].contest_num-3];

                if((dtmp - 1200) >0)info[i].score +=  (dtmp - 1200)*1.0 / 100* 1.5;

            }
            //cout<<i<< " ****** "<<info[i].score<<endl;

        }
        sort(info,info+n,cmp);

        for(i=0; i<m; i++)
        {
            printf("%s %.3f\n",info[i].name,info[i].score);
        }



    }

    return 0;
}
Example #7
0
		int distanceToDestination(vector <string> signs, string destination)
		{
			N=signs.size();
			for(int i=0;i<N;i++)
				for(int j=0;j<(int)signs[i].size();j++)
					if (signs[i][j]==';')
						signs[i][j]=' ';
			hash.clear();
			tot=0;
			int T=getnum(destination);
			vector<pair<int,int> > v[MAXN];
			for(int i=0;i<N;i++)
			{
				stringstream in(signs[i]);
				string str;
				int x;
				while(in>>str>>x)
				{
					int a=getnum(str);
					v[i].pb(mp(a,x));
				}
				sort(v[i].begin(),v[i].end());
			}
			memset(dis,-1,sizeof(dis));
			mem=pool;
			for(int i=0;i<N;i++)
				for(int j=i+1;j<N;j++)
				{
					for(int a=0,b=0;a<(int)v[i].size();a++)
					{
						while(b<(int)v[j].size() && v[j][b].first<v[i][a].first)
							b++;
						if (b<(int)v[j].size())
						{
							if (v[i][a].first==v[j][b].first)
							{
								int nd=v[i][a].second-v[j][b].second;
								if (nd<=0)
									return -1;
								if (dis[i][j]==nd)
									continue;
								if (dis[i][j]==-1)
								{
									dis[i][j]=nd;
									addedge(j,i,nd*MAXN);
									addedge(i,j,-nd*MAXN);
								}
								else
									return -1;
							}
						}
						else
							break;
					}
				}
			if (!spfa())
				return -1;
			int ans=-1;
			for(int i=0;i<N;i++)
				if (i==N-1 || dis[i][N-1]!=-1)
				for(int j=0;j<(int)v[i].size();j++)
					if (v[i][j].first==T)
					{
						ans=v[i][j].second;
						if (i!=N-1)
							ans-=dis[i][N-1];
						break;
					}
			if (ans<0)
				return -1;
			for(int i=0;i+1<N;i++)
				addedge(i,i+1,-1);
			for(int i=0;i<N;i++)
				addedge(N,i,0);
			for(int i=0;i<N;i++)
				dist[i]=oo;
			dist[N]=0;
			bool flag=true;
			for(int i=0;i<N+1 && flag;i++)
			{
				flag=false;
				for(Node *p=pool;p<mem;p++)
					if (dist[p->u]!=oo && dist[p->v]>dist[p->u]+p->w)
					{
						dist[p->v]=dist[p->u]+p->w;
						flag=true;
					}
			}
			if (flag)
				return -1;
			return ans;
		}
int minReversal(string init, string goal) {
	memo.clear();
	int ret = solve(init, goal);
	if (ret >= 10000) return -1;
	return ret;
}
Example #9
0
File: f.cpp Project: kzoacn/OI
inline void solve() {
	n = getnum();
	q = getnum();

	cnt.clear();

	for (int i = 1; i <= n; i++) {
		hus[i].clear();
		wife[i].clear();

		hus[i].push_back(i);
		wife[i].push_back(i);

		hus_idx[i] = i;
		wife_idx[i] = i;
		
		cnt[make_pair(i, i)] = 1;
	}

	int ans = 0, cur_ans = 0;

	for (int t = 1; t <= q; t++) {
		int type = getnum();
		int x = getnum();
		int y = getnum();

		if (type == 1) {
			int fx = hus_idx[x];
			int fy = hus_idx[y];
			if (fx != fy) {
				if (hus[fx].size() > hus[fy].size())
					swap(fx, fy), swap(x, y);
				vector<int> &_ = hus[fx];
				vector<int> &__ = hus[fy];
				for (int i = 0; i < (int)_.size(); i++) {
					int now = _[i];
					info cur = make_pair(fx, wife_idx[now]);	
					info nxt = make_pair(fy, wife_idx[now]);
					if (cnt.count(cur)) {
						int cur_value = cnt[cur];
						if (cnt.count(nxt)) {
							int nxt_value = cnt[nxt];
							update(cur_ans, (ll)cur_value * nxt_value % mod); 
							cnt[nxt] += cur_value;	
						} else {
							cnt[nxt] = cur_value;
						}
						cnt.erase(cur);
					}
					__.push_back(now);	
					hus_idx[now] = fy;
				}
				_.clear();
			}
		} else {
			int fx = wife_idx[x];
			int fy = wife_idx[y];
			if (fx != fy) {
				if (wife[fx].size() > wife[fy].size())
					swap(fx, fy), swap(x, y);
				vector<int> &_ = wife[fx];
				vector<int> &__ = wife[fy];
				for (int i = 0; i < (int)_.size(); i++) {
					int now = _[i];
					info cur = make_pair(hus_idx[now], fx);	
					info nxt = make_pair(hus_idx[now], fy);
					if (cnt.count(cur)) {
						int cur_value = cnt[cur];
						if (cnt.count(nxt)) {
							int nxt_value = cnt[nxt];
							update(cur_ans, (ll)cur_value * nxt_value % mod); 
							cnt[nxt] += cur_value;	
						} else {
							cnt[nxt] = cur_value;
						}
						cnt.erase(cur);
					}
					wife_idx[now] = fy;
					__.push_back(now);	
				}
				_.clear();
			}
		}

		update(ans, (ll)t * cur_ans % mod);
	}

	printf("%d\n", ans);
}
void init(){
    nodes.clear();
    valid = true;
    nNodes = 0;
}
Example #11
0
int BFS(string s)
{
//    debug(s)
    visited.clear();
    visited[s]=1;
    dist[s]=0;
    queue <string> q;
    q.push(s);

    while(!q.empty())
    {
        string u = q.front(); q.pop();
//        debug(u)
        if(u==dest) return dist[u];

        ///1st ta k change
        string v = u;
        v[0]=MOD((int)(v[0]-'a')-1)+'a';
        if(!forbidden[v] && visited[v]==0)
        {
            visited[v]=1;
            dist[v] = dist[u]+1;
            q.push(v);
        }

        v = u;
        v[0]=MOD((int)(v[0]-'a')+1)+'a';
        if(!forbidden[v] && visited[v]==0)
        {
            visited[v]=1;
            dist[v] = dist[u]+1;
            q.push(v);
        }

        v = u;
        v[1]=MOD((int)(v[1]-'a')-1)+'a';
        if(!forbidden[v] && visited[v]==0)
        {
            visited[v]=1;
            dist[v] = dist[u]+1;
            q.push(v);
        }

        v = u;
        v[1]=MOD((int)(v[1]-'a')+1)+'a';
        if(!forbidden[v] && visited[v]==0)
        {
            visited[v]=1;
            dist[v] = dist[u]+1;
            q.push(v);
        }

        v = u;
        v[2]=MOD((int)(v[2]-'a')-1)+'a';
        if(!forbidden[v] && visited[v]==0)
        {
            visited[v]=1;
            dist[v] = dist[u]+1;
            q.push(v);
        }

        v = u;
        v[2]=MOD((int)(v[2]-'a')+1)+'a';
        if(!forbidden[v] && visited[v]==0)
        {
            visited[v]=1;
            dist[v] = dist[u]+1;
            q.push(v);
        }
    }
    return -1;
}
	void clear() {
		m_map.clear();
	}
Example #13
0
int main()
{
	freopen("t.in", "r", stdin);
#ifdef _MSC_VER
	freopen("input.txt","r",stdin);
	uint64 time_used1=0,time_used2=0;
#endif
	memset(C,0,sizeof(C));
	for (int i=0;i<32;i++) for (int j=0;j<=i;j++) C[i][j]=(j==0)?1:(C[i-1][j-1]+C[i-1][j]);
	int n,m;
	double x;
	int testcase;
	preprocess();
	double start_time=(double)clock();
	scanf("%d",&testcase);
	for (int case_id=0;case_id<testcase;case_id++)
	{
		scanf("%d%d%lf",&m,&n,&x);
		if (fabs(x)<1e-6)
		{
			printf("%6e\n",0.0);
			continue;
		}
		if (n>10000000)
		{
			double y=fmod(x*n,pi+pi);
			int d=(int)(y/(pi+pi)*M+0.5);
			if (d<0) d=0;
			if (d>M-1) d=M-1;
			double ret=get_c(n-1,m-1)*f[m][d];
			printf("%6e\n",ret);
			continue;
		}
#ifdef _MSC_VER
		uint64 time1=rdtsc();
#endif
		prepare(n,m,x);
#ifdef _MSC_VER
		uint64 time2=rdtsc();
		time_used1+=time2-time1;
#endif
		memset(visited,false,sizeof(visited));
		double *ret=solve(n,n,m,0,x);
#ifdef _MSC_VER
		uint64 time3=rdtsc();
		time_used2+=time3-time2;
#endif
#ifdef _MSC_VER
		printf("%6e\n",ret[m]);
		double r1=ret[m];
		M2.clear();
		double r2=(n>=1000)?r1:solve2(n,m,x);
		if (fabs(r1-r2)>max(1.0,fabs(r2))*1e-5)
		{
			printf("ERROR %d %d %.2lf\n%.6lf\n%.6lf\n",n,m,x,r1,r2);
			return 0;
		}
		printf("PASSED...\n");
#else
		printf("%6e\n",ret[m]);
		double current_time=(double)clock();
		if (current_time-start_time>(double)CLOCKS_PER_SEC && case_id+1>=5)
			break;
#endif
	}
#ifdef _MSC_VER
	printf("DONE!\n");
	printf("T1 = %.3lf\n",(double)time_used1/1e9);
	printf("T2 = %.3lf\n",(double)time_used2/1e9);
#endif
	return 0;
}
Example #14
0
// return 1 for success, 0 at end of data
// Access (all of) the data for the next epoch. As long as this function
// returns zero, there is more data to be accessed. Ignore passes with
// Status less than zero.
// @param indexMap  map<unsigned int, unsigned int> defined so that all the
//                  data in the current iteration is found at
//                  SatPassList[i].data(j) where indexMap[i] = j.
// @throw if time tags are out of order.
int SatPassIterator::next(map<unsigned int, unsigned int>& indexMap) throw(Exception)
{
   int i,j,numsvs;
   size_t k;
   GSatID sat;

   numsvs = 0;
   indexMap.clear();
   nextIndexMap.clear();

   while(numsvs == 0) {
      if(listIndex.size() == 0) return 0;

      // loop over active SatPass's
      map<GSatID,int>::iterator kt = listIndex.begin();

      kt = listIndex.begin();
      while(kt != listIndex.end()) {
         sat = kt->first;
         i = kt->second;
         j = dataIndex[sat];

         if(SPList[i].Status < 0) continue;     // should never happen

         if(countOffset[sat] + SPList[i].spdvector[j].ndt == currentN) {
            // found active sat at this count - add to map
            nextIndexMap[i] = j;
            numsvs++;

            // increment data index
            j++;
            if(j == SPList[i].spdvector.size()) {     // this pass is done
               indexStatus[i] = 1;

               // find the next pass for this sat
               for(k=i+1; k<SPList.size(); k++) {
                  if(SPList[k].Status < 0)      // bad pass
                     continue;
                  if(SPList[k].sat != sat)      // wrong sat
                     continue;
                  if(indexStatus[k] > 0)        // already done
                     continue;

                  // take this one
                  indexStatus[k] = 0;
                  i = listIndex[sat] = k;
                  dataIndex[sat] = 0;
                  countOffset[sat]
                     = int((SPList[i].firstTime - FirstTime)/DT + 0.5);
                  break;
               }
            }
            else {
               dataIndex[sat] = j;
            }

         }  // end if found active sat at this count

         // increment the iterator
         if(indexStatus[i] > 0) {                // a new one was not found
            listIndex.erase(kt++);  // erasing a map - do exactly this and no more
         }
         else kt++;

      }  // end while loop over active SatPass's

      currentN++;

   }  // end while robs.numSvs==0

   indexMap = nextIndexMap;

   return 1;
}
Example #15
0
File: 1.cpp Project: ak795/acm
int main()
{
    int T;
    cin >> T;
    for (int ti = 0; ti < T; ++ti) {
        int n;
        cin >> n;
        mp.clear();
        for (int i = 1; i <= n; ++i)
            g[i].clear();
        for (int i = 1; i <= n; ++i) {
            string name;
            cin >> name;
            city[i] = name;
            mp[name] = i;
            int p;
            cin >> p;
            for (int j = 0; j < p; ++j) {
                int nr, cost;
                cin >> nr >> cost;
                g[i].push_back(make_pair(cost, nr));
            }
        }
        map<pair<int, int>, int> cache;
        int r;
        cin >> r;
        for (int i = 0; i < r; ++i) {
            string name1, name2;
            cin >> name1 >> name2;
            int idx1 = mp[name1], idx2 = mp[name2];
            if (idx1 == idx2) { cout << 0 << endl; continue; }
            if (idx1 > idx2) swap(idx1, idx2);
            if (((cache).find(make_pair(idx1, idx2)) != (cache).end())) {
                cout << cache[make_pair(idx1, idx2)] << endl;
                continue;
            }
            // for (int j = 1; j <= n; ++j)
            //     dist[j] = -1;
            map<int, long long> dist;
            dist[idx1] = 0;
            set<pair<long long, int> > st;
            for (int j = 0; j < (int)(g[idx1]).size(); ++j)
                st.insert(g[idx1][j]);
            while (!st.empty()) {
                pair<int, int> head = *st.begin();
                st.erase(st.begin());
                int node = head.second, cost = head.first;
                dist[node] = cost;
                cache[make_pair(min(idx1, node), max(idx1, node))] = cost;
                if (node == idx2) break;
                for (int j = 0; j < (int)(g[node]).size(); ++j) {
                    int node2 = g[node][j].second, cost2 = g[node][j].first;
                    if (((dist).find(node2) != (dist).end()) &&
                        dist[node] + cost2 < dist[node2])
                        st.erase(make_pair(dist[node2], node2));
                    st.insert(make_pair(dist[node] + cost2, node2));
                    dist[node2] = dist[node] + cost2;
                }
            }
            cout << dist[idx2] << endl;
        }
    }
}
int main()
{
	//READ();
	int n;
	while(scan(n)!=EOF)
	{
		v.clear();
		mp.clear();

		rep1(i,n)
		{
			int a;
			scan(a);
			if(mp.find(a)==mp.end())
				v.push_back(a);
			mp[a] = true;
		}
		int q;
		scan(q);
		while(q--)
		{
			int a;
			scan(a);
			int pos = lower_bound(v.begin() , v.end() , a) - v.begin();
			int f = -1, l = -1;
			if(pos == n  )
			{
				f = n-1;
			}
			else if( pos == n-1 && v[pos] == a)
			{
				f = n-2;
			}
			else if(pos == 0 && v[0] >  a)
			{
				l = 0;
			}
			else if(pos == 0 && v[0] ==  a)
			{
				l = 1;
			}
			else
			{
				if(v[pos] == a)
				{
					f = pos - 1;
					l = pos + 1;
				}
				else
				{
					f = pos - 1;
					l = pos ;
				}
			}
			if(f >=0 && f!=-1)
			{
				printf("%d ",v[f]);
			}
			else
				printf("%c ",char(88));
			if(l<n && l!=-1)
				printf("%d\n",v[l]);
			else
				printf("%c\n",char(88));
		}
	}
Example #17
0
// main driver  /////////////////////////////////////////////////
int main(int argc, char** argv){

  // declarations and initializations
  vehicle * temp;
  int numScenario = 0;
  int type,row,col;
  char direction;
  int i,j;
  queue<Board> queue;
  stack<int> best;
  int bestMoves;

  int idx;
  string option;
  bool m_solution = false;
  bool m_timer = false;

  // command line arguments
  if(argc >= 2){
    for(idx = 1; idx < argc; idx++){
      option = argv[idx];
      if(option == "-s"){
        m_solution = true;
      }else if(option == "-t"){
        m_timer = true;
      }else{
        cout << "Unknown option: " << option << endl;
        cout << "Usage: ./rush [-s | -t]" << endl;
        return -1;
      }
    }
  }

  // allocate board
  board = new int* [MAX_ROW];
  for(i = 0; i < MAX_ROW; i++){
    board[i] = new int [MAX_COL];
  }

  cin >> numVehicles;

  // start rush solver --------------
  while(numVehicles!= 0){
    numScenario++;

      // init board
      for(i = 0; i < MAX_ROW; i++){
        for(j = 0; j < MAX_COL; j++){
          board[i][j] = -1;
        }
      }

      // read in vehicles
      vehicles = new vehicle [numVehicles];
      for(i = 0; i< numVehicles; i++){
        cin >> type >> direction >> row >> col;
        temp = new vehicle(type,direction,row,col);
        vehicles[i] = *temp;

        // place vehicles onto the board
        if(direction == 'H'){
          for(j = 0; j < type; j++){
            board[row][col+j] = i;
          }
        }else{
          for(j = 0; j < type; j++)
            board[row+j][col] = i;
        }
      }

      // solve it
      Timer t(m_timer);
      t.start();
      if(solve_It(0,queue,best, m_solution, bestMoves)){
        cout << "Scenario "<< numScenario << " requires "
             << bestMoves << " moves" << endl;
        if(m_solution){
          showSolutionSteps(best);
        }
      }
      t.stop();
      if(m_timer){
        cout << "Time: " << t.getElapsedTime() << endl;
      }

      // clear all records
      dejavu.clear();

       // get the next scenario
      cin >> numVehicles;

  } // end rush solver -------------

  return 0;
}
Example #18
0
	void INIParser::process(const wstring& line, bool eof)
	{
		static const RegExp re1 = L"/^(\\w+)=(.*)$/";
		static const RegExp re2 = L"/^\\s*\\[(.+)\\]\\s*$/";
		static const RegExp re3 = L"/\\\\\\[/g";

		static const wstring strTitle = L"title";
		static const wstring strDisabled = L"disabled";
		static const wstring strTrue = L"true";
		static const wstring strLeftBracket = L"[";

		RegExpMatch match;
		bool ret = false;
		if (wantObj && re1.exec(match, line))
		{
			curObj[match.substrings[1]] = match.substrings[2];
		}
		else if (eof || (ret = re2.exec(match, line)))
		{
			wstring strSection;
			if (ret)
			{
				strSection = toLowerCase(match.substrings[1]);
			}
			if (wantObj ? curObj.size() : curList.size())
			{
				// Process current object before going to next section
				switch (curSection)
				{
				case FILTER:
				case PATTERN:
					// create the filter, with certain properties set up
					// do not insert it into the filters set
					// if it's active, it'll be inserted in some subscription we'll later parse
					persistedFilters.insert(Filter::fromObject(curObj));
					break;
				case SUBSCRIPTION:
					// not supported, just record whether the whole subscription is disabled or not
					{
						auto iter = curObj.find(strDisabled);
						subscriptionDisabled =
							iter != curObj.end() && iter->second == strTrue;

						if (hasExcludedSubscriptions)
						{
							auto iterTitle = curObj.find(strTitle);
							subscriptionExcluded = iterTitle != curObj.end() &&
								reExcludedSubscriptions.test(iterTitle->second);
						}
						else
						{
							subscriptionExcluded = false;
						}
					}
					break;
				case SUBSCRIPTION_FILTERS:
				case SUBSCRIPTION_PATTERNS:
				case USER_PATTERNS:
					if (!subscriptionDisabled && !subscriptionExcluded)
					{
						for (size_t i = 0; i < curList.size(); i++)
						{
							const wstring& text = curList[i];
							Filter* filter = Filter::fromText(text);
							// need to reset the disabled property since we don't clear
							// the global filter list between reloads
							ActiveFilter* activeFilter = filter->toActiveFilter();
							if (activeFilter)
							{
								// Only reset disabled property for those not persisted yet
								if (persistedFilters.find(filter) == persistedFilters.end())
									activeFilter->setDisabled(false);
								// just put the filter in INIParser::filters
								filters.insert(activeFilter);
							}
						}
					}
					subscriptionDisabled = false;
					subscriptionExcluded = false;
				}
			}

			// Do clean-up
			curSection = OTHER;
			if (wantObj)
				curObj.clear();
			else
				curList.clear();

			if (eof)
			{
				subscriptionDisabled = false;
				subscriptionExcluded = false;
				return;
			}

			auto iter = sectionMapper.find(strSection);
			if (iter != sectionMapper.end())
			{
				curSection = iter->second;
				switch (curSection)
				{
				case FILTER:
				case PATTERN:
				case SUBSCRIPTION:
					wantObj = true;
					break;
				case SUBSCRIPTION_FILTERS:
				case SUBSCRIPTION_PATTERNS:
				case USER_PATTERNS:
				default:
					wantObj = false;
				}
			}
		}
		else if (!wantObj && line.length() && !subscriptionDisabled && !subscriptionExcluded)
		{
			curList.push_back(replace(line, re3, strLeftBracket));
		}
	}
  vector <int> calcPeakAreas(vector <string> topoData)
  {
    memset(reach, 0, sizeof(reach));
    colorSize.clear();
    color.clear();

    m = topoData.size();
    n = topoData[0].length();
    int c = 1;

    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        if (reach[i][j]) continue;

        queue <pair <int, int> > q;
        char t = topoData[i][j];
        color[c] = t;
        vector <pair<int, int> > s;

        q.push(pair <int, int>(i, j));
        while (!q.empty()) {
          auto p = q.front();
          q.pop();

          if (reach[p.first][p.second])
            continue;

          s.push_back(pair<int, int>(p.first, p.second));
          reach[p.first][p.second] = c;
          for (int ii = -1; ii <= 1; ii++) {
            for (int jj = -1; jj <= 1; jj++) {
              if (ii == 0 && jj == 0) continue;

              if (valid(p.first + ii, p.second + jj) && topoData[p.first + ii][p.second + jj] == t && !reach[p.first + ii][p.second + jj]) {
                q.push(pair<int, int>(p.first + ii, p.second + jj));
              }
            }
          }
        }
        colorSize[c] = s;
        c++;
      }
    }

    vector <int> ret;

    while (true) {
      int ha = -1;
      int hb = -1;
      int hm = 0;
      for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
          if (!lookedCor.count(reach[i][j]) && topoData[i][j] > hm) {
            hm = topoData[i][j];
            ha = i;
            hb = j;
          }
        }
      }

      if (ha == -1)
        break;

      vector <int> v;
      queue <int> cur;
      cur.push(reach[ha][hb]);

      while (!cur.empty()) {
        int c = cur.front();
        cur.pop();
        if (lookedCor.count(c)) continue;

        auto ne = colorSize[c];
        for (int i = 0; i < ne.size(); i++) {
          auto p = ne[i];
          for (int ii = -1; ii <= 1; ii++) {
            for (int jj = -1; jj <= 1; jj++) {
              if (ii == 0 && jj == 0) continue;

              if (valid(p.first + ii, p.second + jj) && 
                  topoData[p.first + ii][p.second + jj] < topoData[p.first][p.second] && 
                  !lookedCor.count(reach[p.first][p.second]))
                cur.push(reach[p.first + ii][p.second + jj]);
            }
          }
        }

        v.push_back(c);
        lookedCor.insert(c);
      }

      ret.push_back(calc(v));
    }

    return ret;
  }
Example #20
0
void init() {
	int i;
	row.clear();
	col.clear();
	mp.clear();
}
void advanceTrial()
{
    cerr << "AdvanceTrial 228 " << endl;
    if ( trialMode == STIMULUSMODE )
    {   bool pretrialMode=trialMode;
        trialMode++;
        trialMode=trialMode%2;
        totalTrialNumber++;
        cerr << "AdvanceTrial 232 " << endl;

        if (block.at("Phase") != 1 )
        {
            cerr << "AdvanceTrial 236 MERDA " << endl;
            double percentOccludedFrames = ((double)occludedFrames/(double)drawingTrialFrame )*100.0;
            if ( percentOccludedFrames > str2num<double>(parameters.find("TestPercentOccludedFrames")) )
            {
                cerr << "Percent occluded frames is" << percentOccludedFrames << " " << occludedFrames << " over " << drawingTrialFrame << endl;
                trial.reinsert(factors);

            }
            drawingTrialFrame=0;
            occludedFrames=0;
        }
        trialFrame=0;
        cerr << "AdvanceTrial 248 MERDA " << endl;
        switch( block.at("Phase") )
        {
        case 0:  //pre-test
        {
            cerr << "AdvanceTrial 253 MERDA " << endl;
            if ( !trial.isEmpty() )	// ci son ancora trial
            {   beepTrial();
                deltaXRods = mathcommon::unifRand(str2num<double>(parameters.find("DeltaXMin")),str2num<double>(parameters.find("DeltaXMax")));
                initStimulus(factors.at("StimulusHeight"),deltaXRods,factors.at("RelDepth"));
                factors = trial.getNext();

                visualRodCenter = Vector3d(0,0,factors.at("Distances"));
                hapticRodCenter  = rodAway;
                initProjectionScreen(visualRodCenter.z()); // scommentato
                // moveMonitorAbsolute(visualRodCenter.z(),homeFocalDistance,SCREENSPEED); //scommentato
                beepTrial();
            }
            else // si prepara per la modalità 1 (adaptation)
            {
                cerr << "AdvanceTrial 270 MERDA " << endl;
                trialMode = HANDONSTARTMODE;
                block = module.getNext();
                initStimulus(factors.at("StimulusHeight"),adaptStimRadius*2,adaptStimRadius*2);
                double zadaptmin = str2num<double>(parameters.find("AdaptZMin"));
                double zadaptmax = str2num<double>(parameters.find("AdaptZMax"));

                if (str2num<int>(parameters.find("AdaptMoveMonitor"))==1)
                    visualRodCenter=Vector3d(0,0,mathcommon::unifRand(zadaptmin,zadaptmax));
                else
                    visualRodCenter=Vector3d(0,0, (zadaptmin+zadaptmax)/2);
                initProjectionScreen( visualRodCenter.z()); //scommentato

                if ( str2num<int>(parameters.find("AdaptHapticFeedback"))==1 )
                    hapticRodCenter = visualRodCenter - Vector3d(0,0,adaptOffsets.at(block1TrialNumber));
                else
                    hapticRodCenter = rodAway;

                /// XXXX fin qua
                //moveRod(Vector3d(0,0,hapticRodCenter.z() ),RODSPEED); //scommentato

                checkBounds();
                beepLong();
            }
            cerr << "AdvanceTrial 290 MERDA " << endl;
            block0TrialNumber++;
        }
        break;
        case 1:  // adaptation
        {
            block1TrialNumber++;
            if ( block1TrialNumber < str2num<int>(parameters.find("AdaptTrials")) )
            {   beepTrial();
                initStimulus(adaptStimHeight,adaptStimRadius*2,adaptStimRadius*2);
                double zadaptmin = str2num<double>(parameters.find("AdaptZMin"));
                double zadaptmax = str2num<double>(parameters.find("AdaptZMax"));

                if (str2num<int>(parameters.find("AdaptMoveMonitor"))==1)
                    visualRodCenter = Vector3d(0,0,mathcommon::unifRand(zadaptmin,zadaptmax));
                else
                    visualRodCenter=Vector3d(0,0, (zadaptmin+zadaptmax)/2);

                if ( str2num<int>(parameters.find("AdaptHapticFeedback"))==1 )
                {
                    hapticRodCenter = visualRodCenter - Vector3d(0,0,adaptOffsets.at(block1TrialNumber));
                    moveMonitorAbsoluteAsynchronous(visualRodCenter.z(),homeFocalDistance,SCREENSPEED);
                    moveRod(hapticRodCenter,RODSPEED);
                }
                else
                {
                    hapticRodCenter = rodAway;
                    moveMonitorAbsolute(visualRodCenter.z(),homeFocalDistance,SCREENSPEED);
                }

                initProjectionScreen( visualRodCenter.z());
                beepTrial();
            }
            else
            {   cerr << "AdvanceTrial 328 MERDA " << endl;
                //beepLong();
                trialMode = HANDONSTARTMODE;
                cerr << "AdvanceTrial 331 MERDA " << endl;
                block  = module.getNext();
                cerr << "AdvanceTrial 333 MERDA " << endl;
                // reset the factors in order to prepare the next test phase
                trial.init(parameters);
                factors.clear();
                factors  = trial.getNext();
                cerr << "AdvanceTrial 338 MERDA " << endl;
                /// ECCO IL BACO
                deltaXRods = mathcommon::unifRand(str2num<double>(parameters.find("DeltaXMin")),str2num<double>(parameters.find("DeltaXMax")));
                cerr << "DISTANCE= " << factors.at("Distances") << endl;
                initStimulus(factors.at("StimulusHeight"),deltaXRods,factors.at("RelDepth"));
                visualRodCenter = Vector3d(0,0,factors.at("Distances"));
                hapticRodCenter = rodAway;

                //moveMonitorAbsolute(visualRodCenter.z(),homeFocalDistance,SCREENSPEED);
                //moveRod(rodAway,RODSPEED);
                initProjectionScreen(visualRodCenter.z());
                cerr << "AdvanceTrial 345 MERDA " << endl;
                beepTrial();
            }
        }
        break;
        case 2:  /// post-test
        {   if ( trial.isEmpty() )
            {   cerr << "AdvanceTrial 352 MERDA " << endl;
                beepLong();
                exit(0);
            }
            else
            {   beepTrial();
                factors = trial.getNext();
                cerr << "AdvanceTrial 363 MERDA " << endl;
                deltaXRods = mathcommon::unifRand(str2num<double>(parameters.find("DeltaXMin")),str2num<double>(parameters.find("DeltaXMax")));
                cerr << "AdvanceTrial 365 MERDA " << endl;
                initStimulus(factors.at("StimulusHeight"),deltaXRods,factors.at("RelDepth"));
                visualRodCenter =  Vector3d(0,0,factors.at("Distances"));
                hapticRodCenter  = rodAway;
                initProjectionScreen(visualRodCenter.z());
                // moveMonitorAbsolute(visualRodCenter.z(),homeFocalDistance,SCREENSPEED); // commentato
                beepTrial();
            }
            block2TrialNumber++;
        }
        break;
        }
        globalTimer.start();
    }
    cerr << "AdvanceTrial 373 MERDA " << endl;
    // Mettere una idle così non perde il primo trial
    idle();
}
		set()
		{
			sz=0;
			element.clear();
		}
 ~RecogInfo()
 {
   tracking_id_buf.clear();
   hist.clear();
 }
Example #24
0
void Maemo::Timed::free_tz_list()
{
    zones.resize(0) ;
    alias_to_zone.clear() ;
}
Example #25
0
int main()
{
	//freopen("F.in", "r", stdin);
	int T; scanf("%d", &T);
	for(int cas = 1; cas <= T; cas++)
	{
		scanf("%d%d", &n, &q);
		for(int i = 1; i <= q; i++)
		{
			char tmp[10]; int x, t;
			scanf("%s%d", tmp, &x);
			if(tmp[0] == 'T') t = 1;
			else if(tmp[0] == 'R') t = 2;
			else t = 3;
			op[i].op = t; op[i].x = x;
			cor[i] = x;
		}
		hash.clear(); maxidx = 0;
		memset(L, 0, sizeof(L));
		std::sort(cor+1, cor+1+q);
		int len = std::unique(cor+1, cor+1+q) - cor;
		for(int i = 1; i < len; i++)
		{
			if(cor[i] - cor[i-1] > 1)
			{
				L[++maxidx] = cor[i-1] + 1;
				hash[L[maxidx]] = maxidx;
			}
			hash[cor[i]] = ++maxidx;
			L[maxidx] = cor[i];
		}
		if(L[maxidx] < n)
		{
			L[maxidx+1] = L[maxidx] + 1;
			++maxidx;
			hash[L[maxidx]] = maxidx;
		}
		//for(int i = 1; i <= maxidx; i++)printf("%d %d\n", L[i], hash[L[i]]); puts("===");
		L[maxidx+1] = n+1;
		memset(num, 0, sizeof(num));
		//printf("maxidx = %d\n", maxidx);
		int qq = std::max(maxidx, 2 * q + 1);
		for(int i = 1; i <= maxidx; i++)
		{
			//printf("now i = %d ..................................\n", i);
			//printf("%d left = %d, len = %d\n", i+qq, L[i], L[i+1] - L[i]);
			update(1, 1, 2*qq, i+qq, L[i+1] - L[i]);
			//for(int p = 1; p <= 15; p++) printf("%d ", num[p]); puts("");
		}
		for(int i = 1; i <= maxidx; i++)
		{
			hash[L[i]] += qq;
			L[i + qq] = L[i];
			L[i] = 0;
		}
		int topcnt = 0;
		printf("Case %d:\n", cas);
		for(int i = 1; i <= q; i++)
		{
			if(op[i].op == 1) // Top
			{
				update(1, 1, 2 * qq, hash[op[i].x], -1);
				hash[op[i].x] = qq - (++topcnt);
				L[hash[op[i].x]] = op[i].x;
				update(1, 1, 2 * qq, hash[op[i].x], 1);
			}
			else if(op[i].op == 2) // Rank
			{
				printf("%d\n", rank(1, 1, 2 * qq, op[i].x));
			}
			else{ // Query
				printf("%d\n", query(1, 1, 2 * qq, 1, hash[op[i].x]));
			}
		}
	}
	return 0;
}
Example #26
0
int main()
{
    string name1,name2;
    while(cin >> name1)
    {
        if(name1 == "END") break;
        nameToNum.clear();
        edges.clear();
        string n1,n2;
        string s;
        int counts = 0;
        for(int i = 0 ; i < 1000;++i)
        {

            for(int j = 0 ; j < 1000;++j)
            {
                maps[i][j] = 999999;

            }
        }
        getchar();
        while(getline(cin,s))
        {
            if(s == "* * *")
            {
                break;
            }
            n1 = s.substr(0,s.find_first_of(" "));
            n2 = s.substr(s.find_first_of(" ")+1);
            if(nameToNum.find(n1) == nameToNum.end())
            {
                nameToNum[n1] = counts++;
            }
            if(nameToNum.find(n2) == nameToNum.end())
            {
                nameToNum[n2] = counts++;
            }
            if( nameToNum[n1] !=  nameToNum[n2])
            {
                edge e;
                e.p1 = nameToNum[n1];
                e.p2 = nameToNum[n2];
                edges.push_back(e);
            }

        }
        int oldCounts = counts;
        cin >> name2;
        getchar();
        while(getline(cin,s))
        {
            if(s == "* * *")
            {
                break;
            }
            n1 = s.substr(0,s.find_first_of(" "));
            n2 = s.substr(s.find_first_of(" ")+1);
            if(nameToNum.find(n1) == nameToNum.end())
            {
                nameToNum[n1] = counts++;
            }
            if(nameToNum.find(n2) == nameToNum.end())
            {
                nameToNum[n2] = counts++;
            }
            maps[nameToNum[n1]][nameToNum[n2] ] = 1;
            maps[nameToNum[n2]][nameToNum[n1] ] = 1;

        }
        for(int i = 0 ; i < counts;++i)
        {
            maps[i][i] = 0;
        }
        int status = 1;
        for(int i = 0 ; i < edges.size();++i)
        {
            int a1 = edges[i].p1;
            int a2 = edges[i].p2;
            if(dij(a1,a2,counts,oldCounts) == 0)
            {
                status = 0;
                break;
            }
        }
        if(status)
        {
            cout << "YES: " << name2 << " is a more detailed version of " << name1 << endl;
        }
        else
        {
            cout << "NO: " << name2 << " is not a more detailed version of " << name1 << endl;
        }

    }
    return 0;
}
Example #27
0
void sortLines3D(int thres){
	map<int, float> lengths;
	map<int,float>::iterator mip;
	vector<Pnt3f> result;

	for(int i(0);i<_LINES.size();i=i+2)
	{
		Vec3f vec = _LINES[i+1] - _LINES[i];
		float length = sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
		lengths[i] = length;
	}

	vector<int> index_vec;
	while(lengths.size() != index_vec.size()){
		float max = -1;
		int max_index;
		for(mip = lengths.begin();mip != lengths.end();mip++ ){
			if(mip->second > max){
				max_index = mip->first;
				max = mip->second;
			}
		}
		result.push_back(_LINES[max_index]);
		result.push_back(_LINES[max_index+1]);
		index_vec.push_back(max_index);
		lengths[max_index] = -1;
	}
	_LINES = result;
	_CONTROLPOINTS.clear();
	_HITPOINTS.clear();
	createFixPoints();
	int lineNumber = (int)_LINES.size()*0.005;
	cout << "line Threshold to create ControlPoints >> "<< lineNumber<<endl;
	for(int i(2);i<thres/*_LINES.size()*/;i=i+2){
		/*int old_i = i;
		i = rand() % _LINES.size();
		if(i %2 != 0 && i+1<=_LINES.size())
			i++;
		else
			i--;
*/
		if(i<lineNumber){
			createControlPoints(i,_LINES[i],_LINES[i+1],5);
			//createControlPoints(i,_LINES[i],_LINES[i+1],5);
		}
		else if(i < lineNumber*2)
			createControlPoints(i,_LINES[i],_LINES[i+1],3);
		else if(i>_LINES.size()-lineNumber)
			createControlPoints(i,_LINES[i],_LINES[i+1],3);
		else
			createControlPoints(i,_LINES[i],_LINES[i+1],3);
		//i =old_i;
		// check number of CP per line
		//cout << "line "<<i<< " no: " << _CONTROLPOINTS[i].size()<<endl;

		Pnt3f first = _CONTROLPOINTS[i][0];
		Pnt3f last = _CONTROLPOINTS[i][_CONTROLPOINTS[i].size()-1];

		if(first[1]>last[1]){
			//cout << "turn around"<<endl;
			vector<Pnt3f> turn;
			for(int v(_CONTROLPOINTS[i].size());v>=0;--v){
				turn.push_back(_CONTROLPOINTS[i][v]);
			}
			_CONTROLPOINTS[i] = turn;
		}

	}

	//exit(0);
}
Example #28
0
void* proxy( void *arg )
{
	pthread_detach( pthread_self() );
	fd_set	writeSet;
	fd_set	readSet;
	int		maxfd = 0;
	unsigned char	buf[MAXBUF];
	char		tempjson[MAXBUF + 1];
	struct timeval	timeout;
	TunnelInfo	*tunnelinfo	= NULL;
	int		maxfdp		= 0;
	int ret=0;
	ssl_info *sslinfo1;
	sockinfo *tempinfo ;
	sockinfo *tempinfo1 ;
	map<int, sockinfo*>::iterator it;
	map<int, sockinfo*>::iterator it1;
	map<int, sockinfo*>::iterator it2;
	int backcode=0;
	while ( proxyrun )
	{

	    if(pingtime+ping<get_curr_unixtime()&&socklist.count(mainsock)!=0&&mainsock!=0)
        {

            #if OPENSSL
            int sendlen = SendPing(mainsock, mainsslinfo->ssl );
            #else
            int sendlen = SendPing(mainsock, &mainsslinfo->ssl );
            #endif
            //发送失败断开连接
            if(sendlen==-1)
            {
                shutdown( mainsock,2);
                mainsock = 0;
                proxyrun=0;
            }
            pingtime = get_curr_unixtime();
	    }

		timeout.tv_sec	= 0;
		timeout.tv_usec = 5000;
		FD_ZERO( &readSet );
		maxfd	= 0;
		maxfdp	= 0;
		FD_ZERO( &writeSet );

		/* 遍历添加 */
		//map<int, sockinfo*>::iterator it;
		for ( it = socklist.begin(); it != socklist.end();  )
		{
			tempinfo = it->second;
			/* 如果未连接才添加,写入监听 */
			if ( tempinfo->isconnect == 0 )
			{
				FD_SET( it->first, &writeSet );
			}
			else{
				FD_SET( it->first, &readSet );
			}
			maxfdp = it->first > maxfdp ? it->first : maxfdp;
			maxfd++;
			//继续遍历
			++it;
		}





		if(maxfd==0)
		{
			sleeps( 500 );
		}

		/*  printf("add ok \r\n"); */
        ret = select( maxfdp + 1, &readSet, &writeSet, NULL, &timeout ); /* 为等待时间传入NULL,则永久等待。传入0立即返回。不要勿用。 */
		if ( ret == -1 && maxfd != 0 )
		{
            echo("select error\r\n");
			continue;
		}

		if ( ret > 0 )
		{
			for ( it1 = socklist.begin(); it1 != socklist.end(); )
			{
			    tempinfo = it1->second;
			    /*等于1才是添加到 readSet的*/
				if (FD_ISSET( it1->first, &readSet )&&tempinfo->isconnect==1 )
				{
                    //先清空
                    memset((char *)buf,0,MAXBUF);
                    sslinfo1 = tempinfo->sslinfo;
                    /* 远程的转发给本地 */
                    if ( tempinfo->istype == 1 )
                    {
                        if ( tempinfo->isconnectlocal == 0 )
                        {
                            backcode=ConnectLocal(sslinfo1,(char *)buf,MAXBUF,&it1,tempinfo,&socklist,tempjson,&tunnellist,tunnelinfo);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }

                        if( tempinfo->isconnectlocal == 2||tempinfo->isconnectlocal == 1  )
                        {
                            backcode=RemoteToLocal(sslinfo1,MAXBUF,(char *)buf,tempinfo,&it1,&socklist);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }
                    }
                    /* 本地的转发给远程 */
                    else if(tempinfo->istype == 2){
                        backcode=LocalToRemote(&it1,(char*)buf,MAXBUF,tempinfo,sslinfo1,&socklist);
                        if(backcode==-1)
                        {
                          continue;
                        }
                    }
                    //控制连接
                    else if(tempinfo->istype ==3){
                         backcode=CmdSock(&mainsock,MAXBUF,(char *)buf,tempinfo,&socklist,tempjson,server_addr,&ClientId,&tunneloklist,&tunnellist);
                         if(backcode==-1)
                         {

                            clearsock( it1->first, tempinfo );
							socklist.erase(it1++);
							mainsock=0;
							tunneloklist.clear();
                            continue;
                         }
                    }


				}
				//可写,表示连接上了
				if ( FD_ISSET( it1->first, &writeSet )&&tempinfo->isconnect==0 )
				{

					if ( tempinfo->isconnect == 0 )
					{
					    //检测连接是否可用
						if (check_sock(it1->first)!= 0 )
						{
						    	//关闭远程连接
							if(tempinfo->istype==2){
                                echo("连接本地失败");
							    shutdown( tempinfo->tosock, 2 );
							}
							clearsock(it1->first,tempinfo);
							socklist.erase(it1++);
							continue;
						}

						/* 置为1 */
						tempinfo->isconnect = 1;

						/* 为远程连接 */
						if ( tempinfo->istype == 1 )
						{
						    //初始化远程连接
                            backcode=RemoteSslInit(&it1,tempinfo,ClientId,&socklist);
                            if(backcode==-1)
                            {
                              continue;
                            }
						}

						//本地连接
                        if ( tempinfo->istype == 2 )
						{
                            it2 = socklist.find(tempinfo->tosock);
                            if(it2 != socklist.end())
                            {
                                tempinfo1 = it2->second;
                                tempinfo1->isconnectlocal=2;
                                /* copy到临时缓存区 */
                                if ( tempinfo1->packbuflen > 0 )
                                {
                                    setnonblocking( it1->first, 0 );
                                    #if WIN32
                                    send(it1->first,(char *)tempinfo1->packbuf,tempinfo1->packbuflen, 0 );
                                    #else
                                    send( it1->first, tempinfo1->packbuf, tempinfo1->packbuflen, 0 );
                                    #endif
                                    setnonblocking(it1->first, 1 );
                                    free( tempinfo1->packbuf );
                                    tempinfo1->packbuf	= NULL;
                                    tempinfo1->packbuflen	= 0;
                                }
                            }
						}
					}
				}
				//继续遍历
				++it1;
			}
		}
		//睡1豪秒,避免CPU过高
		sleeps(2);
	}
	/* 退出 */
	proxyrun = 0;
	return(0);
}
Example #29
0
int Index::scan(const string& currdir, map<string, SNode>& metadata)
{
   dirent **namelist;
   int n = scandir(currdir.c_str(), &namelist, 0, alphasort);

   if (n < 0)
      return -1;

   metadata.clear();

   for (int i = 0; i < n; ++ i)
   {
      // skip "." and ".."
      if ((strcmp(namelist[i]->d_name, ".") == 0) || (strcmp(namelist[i]->d_name, "..") == 0))
      {
         free(namelist[i]);
         continue;
      }

      // check file name
      bool bad = false;
      for (char *p = namelist[i]->d_name, *q = namelist[i]->d_name + strlen(namelist[i]->d_name); p != q; ++ p)
      {
         if ((*p == 10) || (*p == 13))
         {
            bad = true;
            break;
         }
      }
      if (bad)
         continue;

      struct stat s;
      if (stat((currdir + namelist[i]->d_name).c_str(), &s) < 0)
         continue;

      // skip system file and directory
      if (S_ISDIR(s.st_mode) && (namelist[i]->d_name[0] == '.'))
      {
         free(namelist[i]);
         continue;
      }

      SNode sn;
      metadata[namelist[i]->d_name] = sn;
      map<string, SNode>::iterator mi = metadata.find(namelist[i]->d_name);
      mi->second.m_strName = namelist[i]->d_name;

      mi->second.m_llSize = s.st_size;
      mi->second.m_llTimeStamp = s.st_mtime;

      if (S_ISDIR(s.st_mode))
      {
         mi->second.m_bIsDir = true;
         scan(currdir + namelist[i]->d_name + "/", mi->second.m_mDirectory);
      }
      else
      {
         mi->second.m_bIsDir = false;
      }

      free(namelist[i]);
   }
   free(namelist);

   return metadata.size();
}
Example #30
0
void LocalizerImpl::clear()
{
  table.clear();
  unknown.clear();
  language.clear();
}