Example #1
0
 string alienOrder(vector<string>& words) {
 	if (words.empty()) return "";
     vector<vector<int> > edgemap(26);
     vector<int> vis(26, 0), appeared(26, 0);
     for (int i = 0; i < words.size(); i ++) {
     	for (int j = 0; j < words[i].size(); j ++) {
     		appeared[words[i][j] - 'a'] ++;
     	}
     }
     string prev = words[0];
     for (int i = 1; i < words.size(); i ++) {
     	if (words[i] == words[i - 1]) continue;
     	int j = 0;
     	for (j = 0; j < prev.size() && j < words[i].size(); j ++) {
     		if (prev[j] != words[i][j]) break;
     	}
     	if (j == prev.size() || j == words[i].size()) continue;
     	int cur1 = prev[j] - 'a', cur2 = words[i][j] - 'a';
     	edgemap[cur1].push_back(cur2);
     	vis[cur2] ++;
     	prev = words[i];
     }
     queue<int> q;
     string res = "";
     for (int i = 0; i < 26; i ++) {
     	if (vis[i] == 0 && appeared[i] != 0) {
     		q.push(i);
     	}
     }
     while (!q.empty()) {
     	int cnt = q.front();
         char cur = cnt + 'a';
         res += cur;
         q.pop();
         for (int i = 0; i < edgemap[cnt].size(); i ++) {
         	int temp = edgemap[cnt][i];
         	if (vis[temp] > 0) {
         		vis[temp] --;
         		if (vis[temp] == 0) {
         			q.push(temp);
         		}
         	}
         }
     }
     for (int i = 0; i < 26; i ++) {
     	if (vis[i] != 0) return "";
     }
     return res;
 }
Example #2
0
int main(int argc, char *argv[])
{
	int i;
	FILE *fp;

	while (argc > 1 && argv[1][0] == '-')
	{
		switch (argv[1][1])
		{
			case 's':
				strip = 1;
				break;
			default:
				fprintf(stderr, "%s:unknown arg %s\n", argv[0], argv[1]);
				exit(1);
		}
		
		argc--;
		argv++;
	}
	if (argc == 1)
		vis(stdin);
	else
		for (i = 1; i< argc; i++)
			if((fp = fopen(argv[i], "r")) == NULL)
			{
				fprintf(stderr, "%s: can't open %s\n", argv[0], argv[i]);
				exit(1);
			}
			else
			{
				vis(fp);
				fclose(fp);
			}
	exit(0);
}
  vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites)
  {
    vector<unordered_set<int>> g(numCourses, unordered_set<int>());
    for (auto& p : prerequisites) {
      g[p.first].insert(p.second);
      if (g[p.second].find(p.first) != g[p.second].end())
        return {};
    }

    vector<int> ret, vis(numCourses, 0);
    for (int i = 0; i < numCourses; ++i)
      if (!vis[i] && dfs(g, i, ret, vis))
        return {};
    return ret;
  }
    int numIslands(vector<vector<char>> &grid) {
        // size of the given grid
        int n = grid.size();
        if (n == 0) return 0;
        int m = grid[0].size();

        // mark the position (x, y) to 'true' if once it is visited
        vector<vector<bool> > vis(n, vector<bool>(m, false));
        int ans = 0;
        for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (grid[i][j] == '1' && !vis[i][j]) {
            bfs(i, j, n, m, grid, vis);
            ++ans;
        }
        return ans;
    }
 int numIslands(vector<vector<char>>& grid) {
     if(grid.size() == 0 || grid[0].size() == 0) return 0;
     int n=grid.size(), m=grid[0].size();
     vector<vector<bool>> vis(n, vector<bool>(m, false));
     int ans = 0;
     for(int i=0; i<n; i++) {
         for(int j=0; j<m; j++) {
             if(vis[i][j] == false && grid[i][j] == '1') {
                 ans++;
                 dfs(i, j, vis, grid);
             }
         }
     }
     return ans;
 }
Example #6
0
SGraphNodeList *
build_reverse_postorder_list(const SGraph *the_sgraph,
                             const SGraphNodeList *entries,
                             bool do_forward) {
    SGraphNodeList *the_list = new SGraphNodeList;
    ordered_sgraph_list_builder vis(the_sgraph, do_forward, 0, true);
    for (SGraphNodeList::iterator iter = entries->begin();
            iter != entries->end(); iter++) {
        vis.reset_builder(the_sgraph, do_forward, the_list, true);
        SGraphNode node = *iter;
        vis.visit_postorder(node);
        the_list = vis.take_list();
    }
    return the_list;
}
Example #7
0
/*
 * Use vis() to encode characters of src and append encoded characters onto
 * dst. Also encode ", ', $, ` and \, to ensure resulting strings can be
 * represented as '"' delimited strings and safely passed to scripts. Surround
 * result with double quotes if emit_punct is true.
 */
int
pretty_print_string(unsigned char *dst, size_t dstlen, unsigned char *src,
    size_t srclen, int emit_punct)
{
	char visbuf[5];
	unsigned char *origsrc = src;
	int opcount = 0, total = 0;

	if (emit_punct) {
		opcount = snprintf(dst, dstlen, "\"");
		if (opcount == -1)
			return (-1);
		total += opcount;
		if (opcount >= dstlen)
			goto done;
		dstlen -= opcount;
		dst += opcount;
	}

	for (; src < origsrc + srclen; src++) {
		if (*src && strchr("\"'$`\\", *src))
			opcount = snprintf(dst, dstlen, "\\%c", *src);
		else {
			vis(visbuf, *src, VIS_OCTAL, *src+1);
			opcount = snprintf(dst, dstlen, "%s", visbuf);
		}
		if (opcount == -1)
			return (-1);
		total += opcount;
		if (opcount >= dstlen)
			goto done;
		dstlen -= opcount;
		dst += opcount;
	}

	if (emit_punct) {
		opcount = snprintf(dst, dstlen, "\"");
		if (opcount == -1)
			return (-1);
		total += opcount;
		if (opcount >= dstlen)
			goto done;
		dstlen -= opcount;
		dst += opcount;
	}
done:
	return (total);
}
Example #8
0
void
satel(double time)
{
	int i;
	double amean, an, coc, csl, d, de, enom, eo;
	double pp, q, rdp, slong, ssl, t, tp;

	i = 500;
	el = -1;
	time = (time-25567.5) * 86400;
	t = (time - satl.time)/60;
	if(t < 0)
		return; /* too early for satelites */
	an = floor(t/satl.peri);
	while(an*satl.peri + an*an*satl.d1per/2. <= t) {
		an += 1;
		if(--i == 0)
			return;
	}
	while((tp = an*satl.peri + an*an*satl.d1per/2.) > t) {
		an -= 1;
		if(--i == 0)
			return;
	}
	amean = (t-tp)/(satl.peri+(an+.5)*satl.d1per);
	pp = satl.ppi+(an+amean)*satl.d1pp;
	amean *= pipi;
	eo = satl.e0+satl.deo*an;
	rdp = satl.semi/(1+eo);
	enom = amean+eo*sin(amean);
	do {
		de = (amean-enom+eo*sin(enom))/(1.0-eo*cos(enom));
		enom += de;
		if(--i == 0)
			return;
	} while(fabs(de) >= 1.0e-6);
	q = 3963.35*erad/(rdp*(1-eo*cos(enom))/(1-eo));
	d = pp + 2*atan2(sqrt((1+eo)/(1-eo))*sin(enom/2),cos(enom/2));
	slong = satl.pnni + t*satl.rot -
		atan2(satl.ct*sin(d), cos(d));
	ssl = satl.st*sin(d);
	csl = pyth(ssl);
	if(vis(time, atan2(ssl,csl), slong, q)) {
		coc = ssl*sin(glat) + csl*cos(glat)*cos(wlong-slong);
		el = atan2(coc-q, pyth(coc));
		el /= radian;
	}
}
Example #9
0
int main(int argc, char **argv) {
    bool loadvis=true;
    void (*destroy)()=NULL;
    for (int i=0;i<argc;++i) {
      if (strcmp(argv[i],"-nogfx")==0) {
        loadvis=false;
      }
    }
    if (loadvis) {
      Elysia::SharedLibrary vis(Elysia::SharedLibrary::prefix()+"vis"+Elysia::SharedLibrary::postfix()+Elysia::SharedLibrary::extension());
      if (!vis.load()) {
        std::cerr<<"Failed to load vis library\n";
      }else {
        void (*init)();
        init=(void(*)())vis.symbol("init");
        destroy=(void(*)())vis.symbol("destroy");
        (*init)();
      }
    }
    
    Elysia::Vector3f test(0,1,2);
    std::tr1::unordered_map<Elysia::String,Elysia::Vector3f> bleh;
    bleh["ahoy"]=test;
    Elysia::Genome::Genome genes;
    if (argc>1) {
		if(0 == strcmp(argv[1],"-test")){
			int retval= runtest();
            (*destroy)();
            return retval;
		}
        bool retval=loadFile(argv[1],genes);
        if (!retval) {
            printf("Error loading saved file\n");            
        }else {
            printf("Success loading saved file\n");
        }
    }
    Elysia::Brain brain(&(new Elysia::SimpleProteinEnvironment)->initialize(genes));
	//std::vector<Branch *>BranchestoWipe;

    

	
    (*destroy)();
    getchar();

	return 0;
}
Example #10
0
void SCgView::updateSceneRect(const QRectF& rect)
{
    if(!isSceneRectControlled && !sceneRect().contains(rect))
        isSceneRectControlled = true;

    if(isSceneRectControlled)
    {
        QPointF topLeft = mapToScene(0,0);
        QPointF bottomRight = mapToScene(viewport()->width(), viewport()->height());
        QRectF vis(topLeft, bottomRight);
        QRectF result = rect.adjusted(-100, -100, 100, 100).united(vis).united(sceneRect());
        setSceneRect(result);

        emit sceneRectChanged(result);
    }
}
Example #11
0
std::vector<ParticleStateInfo> DecayTree::createDecayProductsFinalStateParticleLists(
    const boost::graph_traits<HelicityTree>::vertex_descriptor& vertex) const {
  std::vector<unsigned int> complete_decendant_list;

  GetVertexDecendants vis(complete_decendant_list, vertex);
  boost::depth_first_search(decay_tree_, boost::visitor(vis));

  std::vector<ParticleStateInfo> fs_particle_list;
  fs_particle_list.reserve(complete_decendant_list.size());
  for (unsigned int i = 0; i < complete_decendant_list.size(); ++i) {
    fs_particle_list.push_back(
        decay_tree_[complete_decendant_list[i]].state_info_);
  }

  return fs_particle_list;
}
Example #12
0
bool bfs(int s, int t) {
	vector<int> vis(nno, 0);
	queue<int> q;
	prev = vector<int>(nno, -1);
	q.push(s), vis[s] = 1;
	while(!q.empty() && !vis[t]) {
		s = q.front(); q.pop();
		for(int i = first[s]; i != -1; i = edges[i].next) {
			if(!vis[edges[i].v] && edges[i].cap - edges[i].flow > 0) {
				q.push(edges[i].v), vis[edges[i].v] = 1;
				prev[edges[i].v] = i;
			}
		}
	}
	return vis[t];
}
Example #13
0
void AuthoringManager::displayGeometryVisualization(EmberEntity& entity) {
	if (!mGeometryVisualizations.count(&entity)) {
		Ogre::SceneNode* node = mWorld.getScene().getSceneManager().getRootSceneNode()->createChildSceneNode();
		GeometryVisualization* vis(nullptr);
		try {
			vis = new GeometryVisualization(entity, node);
		} catch (const std::exception& ex) {
			S_LOG_WARNING("Error when displaying geometry." << ex);
			//just delete the node and return
			node->getCreator()->destroySceneNode(node);
			return;
		}
		sigc::connection conn = entity.BeingDeleted.connect([&]() {hideGeometryVisualization(entity); });
		mGeometryVisualizations.insert(std::make_pair(&entity, std::make_pair(vis, conn)));
	}
}
Example #14
0
    inline typename property_traits<Components>::value_type
    connected_components(Graph& G, DFSVisitor v, Components c, DiscoverTime d,
                         FinishTime f, Color color, directed_tag)
    {
      typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
      typename property_traits<Color>::value_type cc = get(color, Vertex());
      int time = 0;
      depth_first_search(G, record_times(d, f, time, v), color);

      Graph G_T(num_vertices(G));
      transpose_graph(G, G_T);

      typedef typename property_traits<Components>::value_type count_type;

      count_type c_count(0);
      components_recorder<Components, dfs_visitor<> > 
        vis(c, c_count, dfs_visitor<>());

      // initialize G_T
      typename graph_traits<Graph>::vertex_iterator ui, ui_end;
      for (tie(ui, ui_end) = vertices(G_T); ui != ui_end; ++ui)
        put(color, *ui, white(cc));

      typedef typename property_traits<FinishTime>::value_type D;
      typedef indirect_cmp< FinishTime, std::less<D> > Compare;

      Compare fl(f);
      priority_queue<Vertex, std::vector<Vertex>, Compare > Q(fl);

      typename graph_traits<Graph>::vertex_iterator i, j, iend, jend;
      tie(i, iend) = vertices(G_T);
      tie(j, jend) = vertices(G);
      for ( ; i != iend; ++i, ++j) {
        put(f, *i, get(f, *j));
         Q.push(*i);
      }

      while ( !Q.empty() ) {
        Vertex u = Q.top();
        Q.pop();
        if  (get(color, u) == white(cc)) {
          depth_first_visit(G_T, u, vis, color);
          ++c_count; 
        }
      }
      return c_count;
    }
int main( int argc, char** argv ) 
{
  Surface_mesh surface_mesh; 
  
  std::ifstream is(argv[1]) ; is >> surface_mesh ;
  if (!CGAL::is_triangle_mesh(surface_mesh)){
    std::cerr << "Input geometry is not triangulated." << std::endl;
    return EXIT_FAILURE;
  }

  // In this example, the simplification stops when the number of undirected edges
  // drops below 10% of the initial count
  SMS::Count_ratio_stop_predicate<Surface_mesh> stop(0.1);
 
  Stats stats ;
  
  My_visitor vis(&stats) ;
    
  // The index maps are not explicitelty passed as in the previous
  // example because the surface mesh items have a proper id() field.
  // On the other hand, we pass here explicit cost and placement
  // function which differ from the default policies, ommited in
  // the previous example.
  int r = SMS::edge_collapse
           (surface_mesh
           ,stop
            ,CGAL::parameters::get_cost     (SMS::Edge_length_cost  <Surface_mesh>())
                              .get_placement(SMS::Midpoint_placement<Surface_mesh>())
                              .visitor      (vis)
           );
  
  std::cout << "\nEdges collected: "  << stats.collected
            << "\nEdges proccessed: " << stats.processed
            << "\nEdges collapsed: "  << stats.collapsed
            << std::endl
            << "\nEdges not collapsed due to topological constraints: "  << stats.non_collapsable
            << "\nEdge not collapsed due to cost computation constraints: "  << stats.cost_uncomputable 
            << "\nEdge not collapsed due to placement computation constraints: " << stats.placement_uncomputable 
            << std::endl ; 
            
  std::cout << "\nFinished...\n" << r << " edges removed.\n" 
            << num_edges(surface_mesh) << " final edges.\n" ;
        
  std::ofstream os( argc > 2 ? argv[2] : "out.off" ) ; os << surface_mesh ;
  
  return EXIT_SUCCESS ;      
}
Example #16
0
void CGModule::emitModule(){
	
	CGSymFinder vis(this);
	
	size_t k;
	for( k=0;k<frames.size();++k ){
		CGFrame *f=frames[k];
		CGSym *sym=f->fun->sym;
		if( sym->linkage==CG_EXPORT ) exportSyms.insert( sym->value );
		CGAsm *as;
		for( as=f->assem.begin;as!=f->assem.end;as=as->succ ){
			CGStm *t=as->stm;
			if( !t ) continue;
			t->visit( vis );
		}
	}
	
	set<string>::iterator sym_it;
	
	//header
	emitHeader();
	
	//imports
	for( sym_it=importSyms.begin();sym_it!=importSyms.end();++sym_it ){
		emitImport( *sym_it );
	}
	
	//exports
	for( sym_it=exportSyms.begin();sym_it!=exportSyms.end();++sym_it ){
		emitExport( *sym_it );
	}
	
	//frames
	for( k=0;k<frames.size();++k ){
		emitFrame( frames[k] );
	}
	
	//datas
	for( k=0;k<datas.size();++k ){
		emitData( datas[k] );
	}
	
	//footer
	emitFooter();
	
	out.flush();
}
Example #17
0
 bool exist(vector<vector<char>>& board, string word) {
     int m=board.size();
     int n=board[0].size();
     vector<vector<bool> > vis(m,vector<bool>(n,0));
     
     for(int i=0; i<m; i++){
         for(int j=0; j<n; j++ ){
             if(!vis[i][j]){
                 if(dfs(board,i,j,vis,word,0)){
                     return true;
                 }
             }
         }
     }
     
     return false;
 }
  inline typename property_traits<ComponentsMap>::value_type
  connected_components(const Graph& g, ComponentsMap c, 
		       ColorMap color, DFSVisitor v)
  {
    function_requires< VertexListGraphConcept<Graph> >();
    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
    function_requires< ReadWritePropertyMapConcept<ColorMap, Vertex> >();
    function_requires< WritablePropertyMapConcept<ComponentsMap, Vertex> >();
    function_requires< DFSVisitorConcept<DFSVisitor, Graph> >();
    // ...
    typedef typename property_traits<ComponentsMap>::value_type comp_type;
    // c_count initialized to "nil" (with nil represented by max())
    comp_type c_count(std::numeric_limits<comp_type>::max());
    detail::components_recorder<ComponentsMap, DFSVisitor> vis(c, c_count, v);
    depth_first_search(g, vis, color);
    return c_count + 1;
  }
Example #19
0
void AuthoringManager::displaySimpleEntityVisualization(EmberEntity& entity)
{
	if (!mSimpleVisualizations.count(&entity)) {
		Ogre::SceneNode* node = mWorld.getScene().getSceneManager().getRootSceneNode()->createChildSceneNode();
		SimpleEntityVisualization* vis(0);
		try {
			vis = new SimpleEntityVisualization(entity, node);
		} catch (const std::exception& ex) {
			//just delete the node and return
			node->getCreator()->destroySceneNode(node);
			return;
		}
		sigc::connection conn = entity.BeingDeleted.connect(sigc::bind(sigc::mem_fun(*this, &AuthoringManager::simpleEntityVisualizationBeingDeleted), &entity));
		mSimpleVisualizations.insert(SimpleEntityVisualizationStore::value_type(&entity, std::make_pair(vis, conn)));
	}

}
 /**
  * @param board a 2D board containing 'X' and 'O'
  * @return void
  */
 void surroundedRegions(vector<vector<char>>& board) {
     // Write your code here
     int n = board.size();
     if(!n)
         return;
     int m = board[0].size();
     if(!m)
         return;
     vector<int> dx = {-1, 0, 0, 1};
     vector<int> dy = {0, 1, -1, 0};
     for(int i = 0; i < n; i++) {
         for(int j = 0; j < m; j++) {
             if((i == 0 || i == n-1 || j == 0 || j == m-1) && board[i][j] == 'O') {
                 vector<vector<bool> > vis(n, vector<bool>(m, false));
                 list<int> queue;
                 vis[i][j] = true;
                 queue.push_back(i*m+j);
                 while(!queue.empty()) {
                     int top = queue.front();
                     queue.pop_front();
                     int x = top/m, y = top%m;
                     board[x][y] = '-';
                     for(int p = 0; p < 4; p++) {
                         int nx = x+dx[p], ny = y+dy[p];
                         if(nx >= 0 && nx < n && ny >= 0 && ny < m && 
                         board[nx][ny] == 'O' && !vis[nx][ny]) {
                             queue.push_back(nx*m+ny);
                             vis[nx][ny] = true;
                         }
                     }
                 }
             }
         }
     }
     
     for(int x = 0; x < n; x++) {
         for(int y = 0; y < m; y++) {
             if(board[x][y] == 'O')
                 board[x][y] = 'X';
             else if(board[x][y] == '-')
                 board[x][y] = 'O';
         }
     }
 }
Example #21
0
void CorefSolvingXmlLogger::dump(std::ostream& xmlStream, AnalysisGraph* anagraph,   /*SyntacticAnalysis::SyntacticData* sd,*/ AnnotationData* ad) const
{
  if (m_outputSuffix == ".wh.xml")
  {
    xmlStream << "<?xml version='1.0' standalone='no'?>" << std::endl;
    xmlStream << "<!--generated by Amose on ";
    xmlStream << QDateTime::currentDateTime().toString().toUtf8().data();
    xmlStream << "-->" << std::endl;
    xmlStream << "<!DOCTYPE COREF SYSTEM \"coref.dtd\">" << std::endl;
    xmlStream << std::endl;
    xmlStream << "<TEXT>" << std::endl;
    // dump the graph
    DumpXMLAnnotationVisitor vis(xmlStream, /*sd,*/ ad, m_language);
     breadth_first_search(*(anagraph->getGraph()), anagraph->firstVertex(),visitor(vis));
  

    xmlStream << std::endl << std::endl << "</TEXT>" << std::endl;
  }
}
vector<Interval> merge(vector<Interval>& a) {
	vector<Interval> res;
	std::sort(a.begin(), a.end(), cmp);
	vector<int> vis(a.size(), 0);
	for (int i = 0; i < a.size(); i++) {
		if (vis[i])
			continue;
		int end = a[i].end;
		int j = i+1;
		while (j < a.size() && end >= a[j].start) {
			end = max(end, a[j].end);
			vis[j] = 1;
			j++;
		}
		Interval tmp(a[i].start, end);
		res.push_back(tmp);
	}
	return res;
}
Example #23
0
 void dijkstra(int src, IV &dis) {
     set<II> q;
     dis = IV(n, INF);
     BV vis(n);
     q.insert(II(0, src));
     dis[src] = 0;
     while (! q.empty()) {
         II p = *(q.begin()); q.erase(q.begin());
         int d = p.first, v = p.second;
         if (vis[v]) continue;
         vis[v] = true;
         For (EL, e, adj[v]) {
             int d2 = d + e->w;
             if (d2 < dis[e->v]) {
                 dis[e->v] = d2;
                 q.insert(II(d2, e->v));
             }
         }
     }
Example #24
0
//***********************************************************************
// main function for outputing the graph
//***********************************************************************
void SyntacticAnalysisXmlLogger::dumpLimaData(std::ostream& os,
        const LinguisticGraphVertex begin,
        const LinguisticGraphVertex end,
        const AnalysisGraph* anagraph,
        const SyntacticData* syntacticData,
        const uint64_t offsetBegin) const
{
    std::vector< bool > alreadyDumpedTokens;
    std::map< LinguisticAnalysisStructure::Token*, uint64_t > tokens;

    LinguisticGraph* graph = const_cast< LinguisticGraph* >(anagraph->getGraph());
    // go through the graph, add BoWTokens that are not in complex terms
    DumpGraphVisitor vis(*this, os,end, syntacticData,
                         tokens, alreadyDumpedTokens,
                         m_language,offsetBegin);

    os << "<sentence>" << std::endl;
    try
    {
        //breadth_first_search(*graph, begin, visitor(vis));
        // I dont know why the direct call to breadth_first_search does
        // not work (bug when trying to go between vertices 0 and 1; because
        // of the 0->1 edge) :
        // initializing the colors and calling breadth_first_visit
        // works (?)
        LinguisticGraphVertexIt i, i_end;
        uint64_t id = 0;
        alreadyDumpedTokens.resize(num_vertices(*graph));
        for (boost::tie(i, i_end) = vertices(*graph); i != i_end; ++i)
        {
            put(boost::vertex_color, *graph, *i, Color::white());
            alreadyDumpedTokens[id] = false;
            tokens[get(vertex_token, *graph, *i)] = id;
            id++;
        }
        boost::breadth_first_visit(*graph, begin, boost::visitor(vis));
    }
    catch (DumpGraphVisitor::EndOfSearch)
    {   //do nothing: normal ending
    }
    os << "</sentence>" << std::endl;
}
	void setRandomMeans()
	{
		srand(time(NULL));
		vector <bool> vis(values_size);

		for (int i = 0; i < this->K_number; )
		{
			int indx = rand()%values_size;
			if (!vis[indx])
			{
				vis[indx] = 1;
				Randoms.push_back(indx);
				++i;
			}
		}

		//Randoms.push_back(4);
		//Randoms.push_back(7);
		//Randoms.push_back(3);
	}
    ll bfs(int src,int sink){
        queue<int> Q;
        vector<int> prev(n + 1, -1);
        vector<bool> vis(n + 1, false);
        Q.push(src);
        vis[src] = true;
        bool cont = true;
        while(!Q.empty()){
            int v = Q.front();
            Q.pop();
            for(int u : adj[v]){
                if(vis[u] || capacity[v][u] <= 0)
                    continue;
                Q.push(u);
                vis[u] = true;
                prev[u] = v;
                if(u == sink){
                    cont=false;
                    break;
                }
            }
            if(!cont)
                break;
        }
        ll cap = inf;
        for(int v = sink; prev[v] > -1; v = prev[v])
            cap = min(cap, capacity[prev[v]][v]);

        for(int v = sink; prev[v] > -1; v = prev[v]){
            capacity[prev[v]][v] -= cap, capacity[v][prev[v]] += cap;
            if(!edge[v][prev[v]])
                adj[v].push_back(prev[v]), edge[v][prev[v]] = 1;
            if(prev[v] == src)
                return cap;
        }

        if(cap == inf)
            return 0;
        else
            return cap;
    }
Example #27
0
void DetectWithOF5::draw_motions_dense_of()
{
	cv::Mat vis = cv::Mat::zeros(cv::Size(origin_.cols, origin_.rows), CV_32FC3); // rgb 格式为 32FC3

	for (size_t i = 0; i < motions_.size(); i++) {
		Motion &m = motions_[i];

		cv::Mat rgb;
		if (m.dense_sum_dis.cols > 0) {
			cv::Mat ndis, ndir;
			normalize_dis(m.dense_sum_dis, ndis);
			normalize_dir(m.dense_sum_dir, ndir);
			rgb_from_dis_ang(ndis, ndir, rgb);

			cv::Mat r = vis(m.brc);
			rgb.copyTo(r);
		}
	}

	//cv::imshow("dense of", vis);
}
 vector<int> spiralOrder(vector<vector<int> > &matrix) {
     vector<int> ans;
     ans.clear();
     if(matrix.size() == 0) return ans;
     int i = 0, j = 0, op = 0, cnt = 0;
     int n = matrix[0].size(), m = matrix.size();
     if(n==1 && m==1){
         ans.push_back(matrix[0][0]);
         return ans;
     }
     vector<vector<bool> > vis(m + 2, vector<bool>(n + 2, false));
     while(cnt<m*n){
         if(op == 0){
             ans.push_back(matrix[i][j]);
             vis[i][j] = 1;
             j ++;
             cnt ++;
             if(j >= n || vis[i][j]) {j --;i ++;op = 1;}
         }else if(op == 1){
             ans.push_back(matrix[i][j]);
             vis[i][j] = 1;
             i ++;
             cnt ++;
             if(i >= m || vis[i][j]) {i --;j--;op = 2;}
         }else if(op == 2){
             ans.push_back(matrix[i][j]);
             vis[i][j] = 1;
             j --;
             cnt ++;
             if(j < 0 || vis[i][j]) {j ++;i--;op = 3;}
         }else{
             ans.push_back(matrix[i][j]);
             vis[i][j] = 1;
             i --;
             cnt ++;
             if(i < 0 || vis[i][j]) {i ++;j ++;op = 0;}
         }
     }
     return ans;
 }
Example #29
0
main(){
int i,j,n,t,C=0;
scanf("%d",&t);
while(t--){
    scanf("%d",&n);
    for(i=0;i<50;i++)
        for(j=v[i]=test[i]=0;j<50;j++)
            c[i][j]=0;
    while(n--){
        scanf("%d %d",&i,&j);
        i--,j--;
        v[i]++,v[j]++;
        c[i][j]++,c[j][i]++;
    }
    for(i=0;!v[i];i++);
    vis(i);
    for(i=0;i<50;i++)
        if(v[i] && !test[i])break;
    if(i<50){
        puts("some beads may be lost");
        continue;
    }
    for(i=j=0;i<50;i++)
        j+=(v[i]&1);
    if(j){
        puts("some beads may be lost");
        continue;
    }
    for(i=0;i<50;i++)
        if(v[i] && v[i]&1)break;
    if(C++)puts("");
    printf("Case #%d\n",C);
    if(i<50){
        go(i);
        continue;
    }
    for(i=0;v[i]==0;i++);
    go(i);
}
}
Example #30
0
static void
window_buffer_draw(__unused void *modedata, void *itemdata,
    struct screen_write_ctx *ctx, u_int sx, u_int sy)
{
	struct window_buffer_itemdata	*item = itemdata;
	struct paste_buffer		*pb;
	char				 line[1024];
	const char			*pdata, *end, *cp;
	size_t				 psize, at;
	u_int				 i, cx = ctx->s->cx, cy = ctx->s->cy;

	pb = paste_get_name(item->name);
	if (pb == NULL)
		return;

	pdata = end = paste_buffer_data(pb, &psize);
	for (i = 0; i < sy; i++) {
		at = 0;
		while (end != pdata + psize && *end != '\n') {
			if ((sizeof line) - at > 5) {
				cp = vis(line + at, *end, VIS_TAB|VIS_OCTAL, 0);
				at = cp - line;
			}
			end++;
		}
		if (at > sx)
			at = sx;
		line[at] = '\0';

		if (*line != '\0') {
			screen_write_cursormove(ctx, cx, cy + i, 0);
			screen_write_puts(ctx, &grid_default_cell, "%s", line);
		}

		if (end == pdata + psize)
			break;
		end++;
	}
}