int searchPath(TreeNode *current) {
    int extensible_path = current->val;

    int extensible_path_from_left;
    if (current->left != NULL) {
      extensible_path_from_left = searchPath(current->left);
      if (extensible_path < current->val + extensible_path_from_left)
        extensible_path = current->val + extensible_path_from_left;
    }

    int extensible_path_from_right;
    if (current->right != NULL) {
      extensible_path_from_right = searchPath(current->right);
      if (extensible_path < current->val + extensible_path_from_right)
        extensible_path = current->val + extensible_path_from_right;
    }

    if (max_path_sum < extensible_path)
      max_path_sum = extensible_path;

    if (current->left != NULL && current->right != NULL) {
      if (max_path_sum < current->val +
                         extensible_path_from_left +
                         extensible_path_from_right) {
        max_path_sum = current->val +
                       extensible_path_from_left +
                       extensible_path_from_right;
      }
    }

    return extensible_path;
  }
 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
     vector<TreeNode*> p_path=searchPath(root,p);
     vector<TreeNode*> q_path=searchPath(root,q);
     int i;
     for(i=0;i<p_path.size()&&i<q_path.size();i++)
     {
         if(p_path[i]!=q_path[i])
             break;
     }
     if(i==0)
         return NULL;
     else
         return p_path[i-1];
 }
bool searchPath(int i, int ncross, int m, sparsegraph * sg)
{
	int u = path[i-1];
	if (u == session[m][1]) {
		if (i-1 == map[session[m][0]][session[m][1]]) {
			if (best >= 0) {
				if (ncross != best) return false; //two shortest paths have different cross count.
			}
			else {
				if (currentBest > -1 && currentBest < ncross) return false; 
				// there is a non-shortest path has less cross count.
				best = ncross;
			}
		}
		else {
			if (best >= 0 && ncross < best) return false;
			if (currentBest > ncross || currentBest == -1) currentBest = ncross;
		}
		return true;
	}
	for (int iv = 0; iv<sg->d[u]; iv++) {
		int v = sg->e[sg->v[u]+iv];
		int delt=0;
		if (cut1[u] != cut1[v]) delt++;
		if (cut2[u] != cut2[v]) delt++;
		bool isInPath = false;
		for (int j=0; j<i-1; j++) 
			if (path[j] == v) { isInPath = true; break; }
		if (!isInPath) {
			path[i] = v;
			if (!searchPath(i+1, ncross+delt, m, sg)) return false;
		}
	}
	return true;
}
Example #4
0
int main( )
 {
 int i, j, dX, dY, pX, pY, steps, max = 2;
 scanf("%d%d", &r, &c);
 scanf("%d", &n);
 for ( i = 0; i < n; i++ )
 scanf("%d %d", &plants[i].x, &plants[i].y);
 qsort(plants, n, sizeof(PLANT), myCompare);
 for ( i = 0; i < n - 2; i++ )
 for ( j = i + 1; j < n - 1; j++ ) {
 dX = plants[j].x - plants[i].x;
 dY = plants[j].y - plants[i].y;
 pX = plants[i].x - dX;
 pY = plants[i].y - dY;
 if ( pX <= r && pX >= 1 && pY <= c && pY >= 1 )
 continue;
 if ( plants[i].x + max * dX > r )
 break;
 pY = plants[i].y + max * dY;
 if ( pY > c || pY < 1)
 continue;
 steps = searchPath( plants[j], dX, dY );
 if ( steps > max ) max = steps;
 }
 if ( max == 2 ) max = 0;
 printf("%d\n", max);
 return 0;
 }
Example #5
0
void UploadResumeThread::doRun()
{
	assert(m_pUpInfo);

	getWebCore()->resumeUpload(getItemId(), m_szKey.c_str(), *m_pUpInfo);

	const char* localFilePath = getUploadManager()->findUpload(m_szKey.c_str());
	gcString sLocalFP(localFilePath);

	if (localFilePath && validFile(localFilePath))
	{
		onCompleteStrEvent(sLocalFP);
		return;
	}

	//gona try and search for the file in the data/mods/id folder
	const char* appDataPath = getUserCore()->getAppDataPath();
	gcString searchPath("{0}{1}{2}", appDataPath, DIRS_STR, getItemId().getFolderPathExtension());
	gcString sNull("NULL");

	if (doSearch(searchPath.c_str()))
		return;

	if (getUserCore()->isAdmin())
	{
		searchPath = gcString("{0}{1}temp{1}", appDataPath, DIRS_STR);
		
		if (doSearch(searchPath.c_str()))
			return;
	}

	onCompleteStrEvent(sNull);
}
Example #6
0
void DirUtils::getWin32FileList(const wstring& path, vector<wstring>& result)
{
	HANDLE hFind;
	WIN32_FIND_DATA info;

	wstring searchPath (path);
	searchPath.append(L"/*.*");

	hFind = FindFirstFile(searchPath.c_str(), &info);
	if (hFind != INVALID_HANDLE_VALUE) 
	{
		do
		{
			wstring fileName (info.cFileName);
			wstring fullPath = DirUtils::NormalizePath(path + L"/" + fileName);
			if(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if(fileName != L"." && fileName != L"..")
				{
					DirUtils::getWin32FileList(fullPath, result);
				}
			}
			else
			{
				result.push_back(fullPath);
			}
		} while (FindNextFile(hFind, &info) != 0);
	}
}
Example #7
0
File: System.c Project: att/uwin
static void initdirs(void)
{
  char* path = getenv("PATH");
#ifdef FVWM_CONFSUBDIR
  if (!confdir && !(confdir = searchPath(path, FVWM_CONFSUBDIR, NULL, -X_OK)))
    confdir = "/usr/" FVWM_CONFSUBDIR;
#endif
#ifdef FVWM_DATASUBDIR
  if (!datadir && !(datadir = searchPath(path, FVWM_DATASUBDIR, NULL, -X_OK)))
    datadir = "/usr/" FVWM_DATASUBDIR;
#endif
#ifdef FVWM_MODULESUBDIR
  if (!moduledir && !(moduledir = searchPath(path, FVWM_MODULESUBDIR, NULL, -X_OK)))
    moduledir = "/usr/" FVWM_MODULESUBDIR;
#endif
}
Example #8
0
void djvSystemTest::run(int & argc, char ** argv)
{
    DJV_DEBUG("djvSystemTest::run");
    
    QCoreApplication app(argc, argv);
    
    searchPath();
    drives();
}
 int maxPathSum(TreeNode *root) {
   if (root == NULL)
     return 0;
   max_path_sum = root->val;
   // max_path_sum is updated within the function.
   // The return value is the max sum of the extensible path that starts from
   // the node 'current'.
   searchPath(root);
   return max_path_sum;
 }
 vector<TreeNode*> searchPath(TreeNode* root,TreeNode* target)
 {
     vector<TreeNode*> vec;
     if(root->val==target->val)
     {
         vec.push_back(root);
     }
     else if (root->val>target->val)
     {
         vec=searchPath(root->left,target);
         vec.insert(vec.begin(),root);
     }
     else
     {
         vec=searchPath(root->right,target);
         vec.insert(vec.begin(),root);
     }
     return vec;
 }
Example #11
0
IconRec readIcon(Widget shell, char *name)
{
  Window win = DefaultRootWindow(dpy);
  Screen *scrn = XtScreen(shell);
  IconRec icon;
  char fullname[MAXPATHLEN];
  int x, y;
  XpmAttributes attr;
  static XpmColorSymbol none_color = { NULL, "None", (Pixel) 0 };

  none_color.pixel = winInfo.background;

  /* first search for xpm icons: */

  attr.valuemask = XpmReturnPixels | XpmColorSymbols | XpmCloseness;
  attr.colorsymbols = &none_color;
  attr.numsymbols = 1;
  attr.closeness = CLOSENESS;

  if (XpmReadFileToPixmap(dpy, win, searchPath(fullname, resources.pixmap_path, name), &icon.bm, &icon.mask, &attr) == XpmSuccess)
  {
      icon.width = attr.width;
      icon.height = attr.height;
      return icon;
  }

  icon.mask = None;

  /* now search along *bitmapPath: */

  if (XReadBitmapFile(dpy, win, searchPath(fullname, resources.bitmap_path, name), &attr.width, &attr.height, &icon.bm, &x, &y) == BitmapSuccess)
  {
      icon.width = attr.width;
      icon.height = attr.height;
  }

  /* finally search bitmap in standard locations (*bitmapFilePath): */

  else
      icon.bm = XmuLocateBitmapFile(scrn, name, NULL, 0, (int *)&icon.width, (int *)&icon.height, &x, &y);
  return icon;
}
void U2SearchPath::SetReferencePath(const TCHAR* szPath)
{
	if(szPath && szPath[0] != _T('\0'))
	{
		U2Filename searchPath(szPath);
		searchPath.SetFilename(_T(""));
		searchPath.SetExt(_T(""));
		searchPath.FullPath(m_refPath, MAX_PATH);

	}
	else 
		m_refPath[0] = _T('\0');
}
Example #13
0
//Generate different kind of identities
void Graph::generateIdentities2(int length, int numIdents)
{
    if (length % 2 == 1) //only even lengths - easier to make identities
        length++;

    if (length <= 2) //these identities were already used in the first genIdents() function
        return;

    if (numIdents <= 0) //can't generate nonpositively many identities
        return;

    //This function generates numIdents-many identities using blocks of length-many units, raised to
    //the power of the graph's exponent, which naturally makes them equivalent to the identity.
    //Rather than forming identity objects it just sets more edges in the graph, and then
    //trusts in the user to reduce those edges later.

    short block[length]; //used to fill leftWord
    std::vector<short> leftWord; //represents the word that reduces to the identity
    std::list<Node>::iterator leftNode; //the node representing the word leftWord
    std::list<Node>::iterator ident = nodeList.begin(); //the identity of the group

    //each pass through this loop generates a new identity
    for (int i = 0; i < numIdents; i++)
    {
        //this loop fills block with random numbers in the range [1, exponent]
        for (int j = 0; j < length; j++)
            block[j] = (rand() % exponent) + 1;

        //this loop fills leftWord with exponent-many copies of block, yielding a word equal to the identity
        for (int k = 0; k < exponent; k++)
        {
            for (int f = 0; f < length; f++)
                leftWord.push_back(block[f]);
        }

        //now the node representing leftWord can be found and used to form new edges in the graph
        leftNode = searchPath(&leftWord);
        if (leftNode != std::list<Node>::iterator(NULL)) //if word found
        {
            copyNodeEdges(ident, leftNode);
            copyNodeEdges(leftNode, ident);
        }

        //clear containers for the next pass through the loop
        leftWord.clear();
    }

    //done
}
Example #14
0
HKEY QSettingsSysPrivate::openKey( const QString &key, REGSAM access, QString &value , bool global )
{
    HKEY res_key = NULL;
    HKEY scope;
    QString main_key;

    splitKey( key, main_key, value );
    searchPath( scope, main_key, access, global, 1 );

    QT_WA_INLINE(
        RegOpenKeyExW( scope, ( LPCTSTR ) main_key.ucs2(), 0, access, &res_key ),
        RegOpenKeyExA( scope, ( LPCSTR ) main_key.latin1(), 0, access, &res_key ) );

    return res_key;
}
Example #15
0
 bool findFilesRecursive( std::string const& extension, std::string const& path, std::vector<std::string> & results )
 {
   bool found = false;
   boost::filesystem::path searchPath( path );
   DP_ASSERT( directoryExists( searchPath.string() ) );
   for ( boost::filesystem::recursive_directory_iterator dirIt( searchPath ) ; dirIt != boost::filesystem::recursive_directory_iterator() ; ++dirIt )
   {
     if ( _stricmp( dirIt->path().extension().string().c_str(), extension.c_str() ) == 0 )
     {
       results.push_back( dirIt->path().string() );
       found = true;
     }
   }
   return( found );
 }
Example #16
0
int midPath(int IncludingSetLength, int IncludingSet[50], AtoB c[maxnum][maxnum])
{

    //cout << "get mid path" << endl;
    int midDist = 0;
    int distance[maxnum];     // 表示当前点到源点的最短路径长度
    int prevpoint[maxnum];     // 记录当前点的前一个结点

    for(int i=0; i<=200; ++i)
        distance[i] = maxint;

    for (int i = 0; i+1 < IncludingSetLength; ++i)
    {
            
        /*
        * TODO use if {}else{} to cut runtime 
        *
        *
        */

        // if (c[ IncludingSet[i] ][ IncludingSet[i+1] ].dist != inf)
        // {
        //     midDist += c[ IncludingSet[i] ][ IncludingSet[i+1] ].dist;
        // }else{
            midDist += Dijkstra(IncludingSet[i+1], IncludingSet[i], distance, prevpoint, c);
            //cout << IncludingSet[i] << "到" << IncludingSet[i+1] <<"的路径: " << endl;
            searchPath(prevpoint, IncludingSet[i], IncludingSet[i+1]);

        
        
        
    }
    // for (int i = 0; i < IncludingSetLength; ++i)
    // {
            
    //     printf( "access :%d  ", IncludingSet[i]);
    // }
    
    if (midDist >= inf)
    {
        printf( "no result\n" );
    }else{
        printf( "distance :%d \n" ,midDist);
    }
    
    
    return midDist;
}
Example #17
0
Path_To_File::Path_To_File(QWidget *parent) :
    QWidget(parent)
{
    button = new QPushButton(
                QIcon::fromTheme("edit-find"),
                "",
                this);
    path = new QLineEdit(this);
    commonLayout = new QHBoxLayout(this);
    commonLayout->addWidget(button, 0, Qt::AlignLeft);
    commonLayout->addWidget(path);
    setLayout(commonLayout);
    connect(button, SIGNAL(clicked()),
            this, SLOT(searchPath()));
    connect(path, SIGNAL(textChanged(QString)),
            this, SIGNAL(dataChanged()));
}
void FindAllAdornedVariants(const std::wstring& aSearchNameWild, const std::wstring& aSearchPath, std::list<std::wstring>& aAdornedFileNamesFound, const DrivesMap& aDriveMap)
{
	DrivesMap::const_iterator it = aDriveMap.begin();
	DrivesMap::const_iterator end = aDriveMap.end();

	for ( ; it != end ; ++it)
	{
		// drive to search on
		int disk = tolower(it->first);
		std::wstring drive = L"$:";
		drive[0] = disk;

		std::wstring searchPath(aSearchPath);

		// actual readable directory
		std::wstring localDir = it->second->iDir;

		// using ROM/ROFS logs for the z drive, searching for adorned variants is handled later.
		if (disk == 'z' && localDir.empty())
			continue;

		// convert to the local path and see if the file exists on the drive
		ConvertToLocalPath( searchPath, localDir );

		// search this directory 
		std::list<std::wstring> dirContents;
		GetDirContents(searchPath, dirContents);

		std::list<std::wstring>::iterator curr = dirContents.begin();
		std::list<std::wstring>::iterator end = dirContents.end();
		while (curr != end)
		{
			std::wstring dirFile(*curr);

			if (StringUtils::WildcardCompare(aSearchNameWild,dirFile))
			{
				// found an adorned file, add to the list of adorned names found
				std::wstringstream foundFile;
				foundFile << drive << aSearchPath << dirFile;
				aAdornedFileNamesFound.push_back(foundFile.str());
			}

			++curr;
		}
	}
}
Example #19
0
HKEY QSettingsSysPrivate::createKey( const QString &key, REGSAM access, QString &value , bool global )
{
    HKEY res_key = NULL;
    HKEY scope;
    QString main_key;

    splitKey( key, main_key, value );
    searchPath( scope, main_key, access, global, 0 );

    QT_WA_INLINE(
        RegCreateKeyExW( scope, ( LPCTSTR ) main_key.ucs2(), 0, NULL,
                         REG_OPTION_NON_VOLATILE, access, NULL, &res_key , NULL ),
        RegCreateKeyExA( scope, ( LPCSTR ) main_key.latin1(), 0, NULL,
                         REG_OPTION_NON_VOLATILE, access, NULL, &res_key , NULL ) );

    return res_key;
}
Example #20
0
int invRTSGame::moveToPoint(lua_State* L)
{
	invTask* t = new invTask;
	t->type = invTask::MOVING_TO_POINT;
	t->unitID = lua_tonumber(L, 3);
	t->e = findEntity(t->unitID);

	Vec3f* dest = new Vec3f(lua_tonumber(L, 1), 0.f, lua_tonumber(L, 2));
	t->data[0] = (void*)pfgrid;
	t->data[1] = (void*)dest;
	t->e->deletePath();
	t->e->path = searchPath(t->e->pos.x, t->e->pos.z, dest->x, dest->z, pfgrid);
	
	setTaskInfo(t, L);
	tasks.addBack(t);

	return 0;
}
Example #21
0
Bool16 CheckWorldDirAccess(char* pathBuff)
{

    Bool16 result = true;
    struct stat statData;
    char searchBuffer[kMaxPathLen] = {};
    StrPtrLen searchPath(searchBuffer, kMaxPathLen -1);
    StrPtrLen thePath(pathBuff);
    
    if (thePath.Len <= searchPath.Len)
    {   
        memcpy(searchBuffer,thePath.Ptr, thePath.Len);
    
        while ( (true == result) && (0 != GetPathParentDestructive(&searchPath, &searchPath, kMaxPathLen)) ) // loop until fail or have checked full directory path and file
        {
            result = false;
                        
            do // once only check for the current entity
            {
                //qtss_printf("stat on %s \n",searchBuffer);
                if (0 != stat(searchBuffer,&statData))
                {   
                    //qtss_printf("no world access to path =%s\n",searchBuffer);
                    result = true; // let the server deal with this one
                    break;
                }           
                    
                //qtss_printf("statData.st_mode = %x \n",statData.st_mode);  
                if (0 == (statData.st_mode & 0001) )
                {   
                    //qtss_printf("no world access to path =%s\n",searchBuffer);
                    result = false;
                    break;
                }
        
                result = true;
                    
            
            } while (false);
        } ;
    }

    return result;
}  
bool GameInfo::init(const std::wstring &moDirectory, const std::wstring &gamePath)
{
  if (s_Instance == nullptr) {
    if (gamePath.length() == 0) {
      // search upward in the directory until a recognized game-binary is found
      std::wstring searchPath(moDirectory);
      while (!identifyGame(searchPath)) {
        size_t lastSep = searchPath.find_last_of(L"/\\");
        if (lastSep == std::string::npos) {
          return false;
        }
        searchPath.erase(lastSep);
      }
    } else if (!identifyGame(gamePath)) {
      return false;
    }
  }
  return true;
}
Example #23
0
int invRTSGame::moveToEntity(lua_State* L)
{
	invTask* t = new invTask;
	t->type = invTask::MOVING_TO_ENTITY;
	t->unitID = lua_tonumber(L, 2);
	t->e = findEntity(t->unitID);

	invEntity* target = findEntity(lua_tonumber(L, 1));
	Vec3f* dest = &target->pos;
	t->data[0] = (void*)pfgrid;
	t->data[1] = (void*)dest;
	t->data[2] = (void*)target;
	t->e->deletePath();
	t->e->path = searchPath(t->e->pos.x, t->e->pos.z, dest->x, dest->z, pfgrid);

	setTaskInfo(t, L);

	tasks.addBack(t);

	return 0;
}
Example #24
0
	int Archive::Impl::BinarySearch(const rString& path, int begin, int end) {
		int mid = (begin + end) / 2;
		PathData pathData;
		GetEntryInfo(mid, pathData);

		std::vector<char> searchPathBuffer(pathData.pathSize);
		archiveStream->Seek(AbsolutePathOffset(pathData.pathOffset), rSeekMode::Beginning);
		archiveStream->Read(searchPathBuffer.data(), pathData.pathSize);

		rString searchPath(searchPathBuffer.data(), searchPathBuffer.size());

		int result = path.compare(searchPath);

		if (result == 0)
			return mid;
		else if (begin == end)
			return -1; // item not found;
		else if (result < 0)
			return BinarySearch(path, begin, mid - 1);
		else //(result > 0)
			return BinarySearch(path, mid + 1, end);
	}
bool isMerger(int m, int c1, int c2, sparsegraph * sg)
{
	for (int i=0,testbit=1; i<n-1; i++, testbit<<=1) { 
		cut1[i] = (c1 & testbit)? 1:0; 
		cut2[i] = (c2 & testbit)? 1:0; 
	}
	cut1[n-1] = cut2[n-1] = 1; path[0] = session[m][0];
	currentBest = best = -1;
	if (searchPath(1, 0, m, sg)) {
		/*
		printf("s%d: ", m);
		for (int i=0; i<n; i++)
			if (cut1[i]) printf("%d ", i);
		printf("; ");
		for (int i=0; i<n; i++)
			if (cut2[i]) printf("%d ", i);
		printf("\n");
		*/
		return true;
	}
	return false;
}
Example #26
0
int GetSteamUsers(std::vector<gcString> &vUsers)
{
	std::string steampath = UTIL::OS::getConfigValue(STEAMPATH);

	if (steampath.size() == 0)
		return 0;

	gcString searchPath("{0}\\steamapps\\", steampath);

	std::vector<UTIL::FS::Path> fileList;
	UTIL::FS::getAllFolders(UTIL::FS::Path(searchPath, "", false), fileList);

	int num = 0;

	for (size_t x = 0; x < fileList.size(); x++)
	{
		gcString strFolder(fileList[x].getLastFolder());
		std::transform(strFolder.begin(), strFolder.end(), strFolder.begin(), ::tolower);

		int y = 0;

		while (g_szIgnoredFolders[y])
		{
			if (strFolder == g_szIgnoredFolders[y])
				break;

			++y;
		}

		if (g_szIgnoredFolders[y])
			continue;

		vUsers.push_back(fileList[x].getLastFolder());
		num++;
	}

	return num;
}
Example #27
0
void Directory::Update()
{
    m_Files.clear();
    m_Subdirs.clear();

    WIN32_FIND_DATA fData;

    Path searchPath( m_Path.c_str() );
    searchPath.SetFile( "*" );
    searchPath.SetExt ( "*" );

    HANDLE h = FindFirstFile( searchPath.GetFullPath(), &fData );
    uint32_t err = GetLastError();
    if (h == INVALID_HANDLE_VALUE) return;

    do
    {
        const char* fname = fData.cFileName;
        if (fname[0] != '.') 
        {
            uint32_t flags = fData.dwFileAttributes;
            if (flags & FILE_ATTRIBUTE_DIRECTORY)
            {
                char path[_MAX_PATH];
                _makepath( path, NULL, m_Path.c_str(), fname, NULL );
                m_Subdirs.push_back( Directory( fname, path ) );
                m_Subdirs.back().Update();
            }
            else if (!(flags & FILE_ATTRIBUTE_SYSTEM)) 
            {
                m_Files.push_back( fname );
            }
        }
    } while (FindNextFile( h, &fData ));

    FindClose( h );
}
Example #28
0
int hatingFlog()
{
	int dx, dy;
	int max = 2;
	int tmpStep;
	input();

	std::sort(plants, plants + n);

	for (int i = 0; i < n - 1; ++i)
	{
		for (int j = i + 1; j < n; ++j)
		{
			dx = plants[j].x - plants[i].x;
			dy = plants[j].y - plants[i].y;
			//如果第一个点的前一个点还在field内,则肯定不是最优答案的起点,换第二个点。
			if (plants[i].x - dx >= 1 && plants[i].x - dx <= c && plants[i].y - dy >= 1 && plants[i].y <= r)
				continue;
			//如果第一个点经过比max还小的step就越界了,肯定也不可能满足条件。
			//由于是按x排好序的,再往后换第二个点必然也不满足条件,所以换第一个点。
			if (plants[i].x + dx * (max - 1) > r)
				break;

			//如果y方向过早越界
			if (plants[i].y + dy * (max - 1) > c || plants[i].y + dy * (max - 1) < 1)
				continue;

			//如果三种提前的排除无法排除该店,那么算这条路径的step,看其是否为最大。
			int tmpStep = searchPath(dx, dy, plants[i]);
			if (tmpStep > max) max = tmpStep;

		}
	}
	if (max <= 2) max = 0;
	return max;
}
Example #29
0
void search_route(char *topo[5000], int edge_num, char *demand)
{
    //unsigned short result[] = {2, 6, 4};
    
    AtoB distM[maxnum][maxnum];
    
    int begin;
    int end;
    int id;
    int dist;

    
    /*
    *init the matrix
    *
    *
	*/

    //TODO use dist[] not matrix to change 600

	for (int i = 0; i < 100; ++i)
	{
		for (int j = 0; j < 100; ++j)
		{
			if (i == j)
			{
				distM[i][j].dist = 0;
			}else{
				distM[i][j].dist = inf;
			}
		}
	}



    // for (int i = 0; i < edge_num; i++){
    	
    //     	int begin = ((int)*(topo[i]+2) - 48);
    //     	int end = ((int)*(topo[i]+4) - 48);

    //     	distM[begin][end].id = ((int)*(topo[i]) - 48);
        	
    //     	distM[begin][end].dist = ((int)*(topo[i]+6)-48);
        	
    // }
    
    /* format the matrix */
    for (int i = 0; i < edge_num; ++i)
    {
    	char* token = strtok( topo[i], ",");
    	int k = 0;
    	while( token != NULL ) {

	        //printf( "result is %s\n", result );
	        if (k == 0)
	        {
	        	id = atoi(token);
	        }else if (k == 1)
	        {
	        	begin = atoi(token);
	        }else if (k == 2)
	        {
	        	end = atoi(token);
	        }else if (k ==3)
	        {
	        	dist = atoi(token);
	        }
    		k++;
	        token = strtok( NULL, "," );

   		}     
    	

    	distM[begin][end].id = id;
        	
    	distM[begin][end].dist = dist;

        printf( "from %d to %d ,token is :%d ", begin, end, distM[begin][end].dist );

	    //token = strtok( NULL, ",");
	    printf("\n");
    }
 
	printf("\n\n\n\n");

/*
*	get the necessary point which is in demand.csv
*
*/
	
	/* for demand */

    int SourceID;
    int DestinationID;
    int IncludingSet[50];
	
	//int len = strlen(demand);
	//printf("length is :%d\t",len);
	char* token = strtok( demand, ",|");
	int i = 0;
	int IncludingSetLength = 0;

    while( token != NULL )
    {
        /* While there are tokens in "string" */
        //printf( "token is :%s ", token );

    	if (i == 0)
    	{
    		SourceID = atoi(token);
    	}else if (i ==1)
    	{
    		DestinationID = atoi(token);
    	}else if (i >= 2)
    	{
    		IncludingSet[IncludingSetLength] = atoi(token);
    		IncludingSetLength++;
    	}

        /* Get next token: */
    	
        token = strtok( NULL, ",|");
        i++;
    }
    printf( "start :%d \n", SourceID );
    printf( "end :%d \n", DestinationID );
    printf( "number :%d \n", IncludingSetLength);
    // for (int i = 0; i < IncludingSetLength; ++i)
    // {
        
    // 	printf( "access :%d ", IncludingSet[i] );

    // }
    

    int arrNum = 1;
    int midDist = inf;

    int totalDist = inf;

    int firstDist = inf;
    int lastDist = inf;

    int tempDist = 0;

    int firstdistance[maxnum];     // 表示当前点到源点的最短路径长度
    int firstprevpoint[maxnum];     // 记录当前点的前一个结点

    for(int i=0; i<=edge_num/2; ++i)
        firstdistance[i] = maxint;

    int lastdistance[maxnum];     // 表示当前点到源点的最短路径长度
    int lastprevpoint[maxnum];     // 记录当前点的前一个结点

    for(int i=0; i<=edge_num/2; ++i)
        lastdistance[i] = maxint;

    int copyIncludingSet[50];

    do 
    {  
        /* Dijkstra(int SourceID, int DestinationID, int distance[], int prevpoint[], AtoB distM[][]);*/

        midDist = midPath(IncludingSetLength, IncludingSet, distM);
        firstDist = Dijkstra(IncludingSet[0] , SourceID, firstdistance, firstprevpoint, distM);
        lastDist = Dijkstra(DestinationID, IncludingSet[IncludingSetLength], lastdistance, lastprevpoint, distM);

        tempDist = firstDist + midDist + lastDist;
        cout << firstDist << " " << midDist << " " << lastDist << "\n" ;
        if (tempDist < totalDist)
        {
            totalDist = tempDist;
            //copy the shortest IncludingSet to the new array
            //the last time we copied is the shortest IncludingSet
            
            //memcpy(copyIncludingSet,IncludingSet, IncludingSetLength*sizeof(int)); 

            for (int i = 0; i < IncludingSetLength; ++i)
            {
                copyIncludingSet[i] = IncludingSet[i];
            }
            cout << "\n\n\n\n\n\n\n\n\n\n copy \n\n\n\n\n\n\n" ;
            
        }

        arrNum++;
            
    }while (next_permutation(IncludingSet, (IncludingSet+IncludingSetLength)));

    cout << "array number is :" << arrNum-1 << endl;
    
    printf("\n\n\n\n\n");
    for (int i = 0; i < IncludingSetLength; ++i)
    {
        printf("access %d", copyIncludingSet[i]);
    }
    printf("\n\n\n\n\n");

    midDist = midPath(IncludingSetLength, IncludingSet, distM);

    firstDist = Dijkstra(IncludingSet[0] , SourceID, firstdistance, firstprevpoint, distM);
    searchPath(firstprevpoint, SourceID, IncludingSet[0]);

    lastDist = Dijkstra(DestinationID, IncludingSet[IncludingSetLength], lastdistance, lastprevpoint, distM);
    searchPath(lastprevpoint, IncludingSet[IncludingSetLength], DestinationID);

    printf("\n\n\n\n\n");




 //    int distance[maxnum];     // 表示当前点到源点的最短路径长度
 //    int prevpoint[maxnum];     // 记录当前点的前一个结点

	// for(int i=0; i<=edge_num/2; ++i)
 //        distance[i] = maxint;

 //    int case0;

 //    // you can set startpoint and endpoint as you want
 //    case0 = Dijkstra(DestinationID, SourceID, distance, prevpoint, distM);
 
 //    // 最短路径长度
 //    cout << "startPoint到endPoint的最短路径长度: " << case0 << endl;

	// cout << "tartPoint到endPoint的的路径: " << endl;
	// searchPath(prevpoint, SourceID, DestinationID);

/* wirte to file */
    for (int i = 0; i < 3; i++)
        record_result(*topo[i]);
}
Example #30
0
int FILE_get_directory(
		const string&		path,
		vector<string> *	out_files,
		vector<string> *	out_dirs)
{
#if IBM

	string				searchPath(path);
	WIN32_FIND_DATA		findData;
	HANDLE				hFind;
	int					total = 0;

	searchPath += string("\\*.*");

	hFind = FindFirstFile(searchPath.c_str(),&findData);
	if (hFind == INVALID_HANDLE_VALUE) return -1;

	do {

		if(strcmp(findData.cFileName,".") == 0 ||
			strcmp(findData.cFileName,"..") == 0)
		{
			continue;
		}

		if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if(out_dirs)
				out_dirs->push_back(findData.cFileName);
		}
		else
		{
			if(out_files)
				out_files->push_back(findData.cFileName);
		}
		
		++total;

	} while(FindNextFile(hFind,&findData) != 0);


	FindClose(hFind);
	return total;

#elif LIN || APL

	int total=0;
	DIR* dir = opendir ( path.c_str() );
	if ( !dir ) return -1;
	struct dirent* ent;

	while ( ( ent = readdir ( dir ) ) )
	{
		struct stat ss;
		if ( ( strcmp ( ent->d_name, "." ) ==0 ) ||
		        ( strcmp ( ent->d_name, ".." ) ==0 ) )
			continue;

		string	fullPath ( path );
		fullPath += DIR_CHAR;
		fullPath += ent->d_name;

		if ( stat ( fullPath.c_str(), &ss ) < 0 )
			continue;
		total++;
		
		if(S_ISDIR ( ss.st_mode ))
		{
			if(out_dirs)
				out_dirs->push_back(ent->d_name);
		}
		else
		{
			if(out_files)
				out_files->push_back(ent->d_name);
		}
	}
	closedir ( dir );

	return total;

#else
#error not implemented
#endif
}