Exemplo n.º 1
0
int main()
{

	freopen("secure.in", "r", stdin);
	freopen("secure.out", "w", stdout);

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

        for (i = 1; i <= n; i++)
        {
        	scanf("%d", &clr[i]);
        	if (clr[i] == 1)
        		odd++;
		else
		if (clr[i] == 2)
			even++;
        }


	for (i = 1; i <= m; i++)
	{
		scanf("%d%d%d", &u, &v, &c);
		//if (clr[u] != clr[v] || (clr[u] == 0 && clr[v] == 0))
		//{
			add(u, v, c);
			add(v, u, c);
//		}
	}

	inf = 1000*1000*1000;
	inf *= 1000;
	from = 1;
	if (even < odd)
		from = 2;

	ans = inf;
	

	for (i = 1; i <= n; i++)
		if (clr[i] == from)
		{
			for (j = 1; j <= n; j++)
				d[j] = inf;
			d[i] = 0;
			s.insert(make_pair(d[i], i));
			while (!s.empty())
			{
				u = s.begin() -> second;
				s.erase(make_pair(d[u], u));
				j = st[u];
				while (j != 0)
				{
					int v = data[j];
					if (d[v] > d[u] + w[j])
					{
						s.erase(make_pair(d[v], v));
						d[v] = d[u] + w[j];
						s.insert(make_pair(d[v], v));
					}
					j = nxt[j];
				}
			}
			
			for (j = 1; j <= n; j++)
				if (clr[j] != from && clr[j] != 0)
					if (d[j] < ans)
					{
						ans = d[j];
						x = i;
						y = j;
					}
		}
	if (ans != inf)
		printf("%d %d %d", x, y, ans);
	else
		printf("%d", -1);

	return 0;
}
Exemplo n.º 2
0
void gornasredniaiden()
{
    printf("%d/1 ",*unikaty.begin());
}
Exemplo n.º 3
0
/* train a retention model; the svr_index is given as a parameter */
int RetentionModel::TrainRetentionModel(const set<string> &aa_alphabet, const map<string, double> &index,
    const bool normalized_rts, vector<PSMDescription*> &psms) {
  if (VERB >= 4) {
    cerr << "Training retention model..." << endl;
  }
  // normalize
  if (!normalized_rts) {
    PSMDescriptionDOC::setPSMSet(psms);
    sub_ = PSMDescriptionDOC::normSubRT_;
    div_ = PSMDescriptionDOC::normDivRT_;
    PSMDescriptionDOC::normalizeRetentionTimes(psms);
  }
  // set the amino acids alphabet and the index
  vector<string> alphabet(aa_alphabet.begin(), aa_alphabet.end());
  retention_features_.set_amino_acids_alphabet(alphabet);
  retention_features_.set_svr_index(index);
  // set the active features; this should be modified as we add more feature groups
  bitset<RetentionFeatures::NUM_FEATURE_GROUPS> tmp;
  if (index.size() <= 20) {
    retention_features_.set_active_feature_groups(
        tmp.set(RetentionFeatures::INDEX_NO_PTMS_GROUP));
  } else {
    retention_features_.set_active_feature_groups(
        tmp.set(RetentionFeatures::INDEX_PHOS_GROUP));
  }
  // compute the amino acid features
  retention_features_.ComputeRetentionFeatures(psms);
  // normalize the features
  NormalizeFeatures(true, psms);
  // save the sub and the div
  vsub_ = the_normalizer_->GetVSub();
  vdiv_ = the_normalizer_->GetVDiv();
  
  /*
  //MT: prints the normalized features for Xuanbin's project
  for (size_t j = 0; j < psms.size(); ++j) {
    cout << psms[j].peptide;
    for (int i = 0; i < retention_features_.GetTotalNumberFeatures(); ++i) {
      cout << " " << psms[j].getRetentionFeatures()[i];
    }
    cout << std::endl;
  }
  cerr << "Finished printing out features" << std::endl;
  */
  
  // initialize a RBF SVR
  if (svr_model_) {
    delete svr_model_;
  }
  InitSVR(false);
  // calibrate the model
  int number_features = retention_features_.GetTotalNumberFeatures();
  //cout << number_features << endl;
  //cout << psms[0] << endl;
  svr_model_->CalibrateModel(psms, number_features);
  // train the model
  svr_model_->TrainModel(psms, number_features);
  // unnormalize the retention time
  PSMDescriptionDOC::unnormalizeRetentionTimes(psms);
  if (VERB >= 4) {
    cerr << "Done." << endl << endl;
  }
  return 0;
}
Exemplo n.º 4
0
int main() {
	//ios_base::sync_with_stdio(false);
	FastInput input;
	int nCases = input.readNextUnsigned();
	for(int caseNum=1;caseNum<=nCases;++caseNum) {
		int N = input.readNextUnsigned();
		int M = input.readNextUnsigned();
		int A = input.readNextUnsigned();

		int nEdges = 0;
		int myMaxWeight = 0;
		int myMinWeight = 1000000;
		for(int i=0;i<M;++i) {
			int u = input.readNextUnsigned();
			int v = input.readNextUnsigned();
			int w = input.readNextUnsigned();
			--u;--v;
			if (w >= A) continue;
			edges.insert(make_pair(w,make_pair(u,v)));
			//edgesCounting[w].push_back(make_pair(u,v));
			//myMaxWeight = max(myMaxWeight, w);
			//myMinWeight = min(myMinWeight, w);
			//adj[v].push_back({u,w});
		}
		UnionFind uf(N);
		//sort in linear time
		/*
		weightTotal = 0;
		for(int weight = myMinWeight; weight<=myMaxWeight;++weight) {
			for(int j=0;j<edgesCounting[weight].size();++j) {
				int xroot = uf.find(edgesCounting[weight][j].first);
				int yroot = uf.find(edgesCounting[weight][j].second);
				if (xroot != yroot) {
					uf.Union(xroot,yroot);
					weightTotal += weight;
				}
			}
			edgesCounting[weight].clear();
		}
		*/
		
		weightTotal = 0;
		//sort(edges,edges + nEdges); //stable sort
		while (edges.size()) {
			auto temp = edges.begin();
			int w = temp->first;
			int xroot = uf.find(temp->second.first);
			int yroot = uf.find(temp->second.second);

			edges.erase(temp);

			if (xroot != yroot) {
				uf.Union(xroot,yroot);
				weightTotal += w;
			}
		}
		/*
		for(int i=0;i<nEdges;++i) {
			int xroot = uf.find(edges[i].second.first);
			int yroot = uf.find(edges[i].second.second);
			if (xroot != yroot) {
				uf.Union(xroot,yroot);
				weightTotal += edges[i].first;
			}
		}
		*/
		nComponents = 0;
		for(int i=1;i<=N;++i) {
			int place = uf.find(i);
			if (!mySet[place]) {
				++nComponents;
				mySet[place] = 1;
			}
		}
		mySet = 0;
		int ans = weightTotal + A * nComponents;
		cout << "Case #" << caseNum << ": " << ans << " " << nComponents << '\n';

	}
	return 0;
}
Exemplo n.º 5
0
bool cmp1(set<int>& a, set<int>& b) {
    return *a.begin() < *b.begin();
}
Exemplo n.º 6
0
int main()
{
    //freopen("in.txt", "r", stdin);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int h, q, i, k;
    long long l, r, lo = 1, hi = 2;
    vector <pair <long long, long long> > v, v1;
    cin >> h >> q;
    for(int i = 0; i < h - 1; i++)
    {
        lo *= 2;
        hi *= 2;
    }
    hi--;
    s.insert({lo, hi});
    while(q--)
    {
//        for(auto it = s.begin(); it != s.end(); it++)
//            cout << it -> first << " " << it -> second << " ";
        //cout << "\n";
        v.clear();
        v1.clear();
        cin >> i >> l >> r >> k;
        for(int j = i; j < h; j++)
        {
            l *= 2;
            r = r*2 + 1;
        }
        if(k == 1)
        {
            auto it = s.upper_bound({l, l}), it2 = s.upper_bound({r, hi + 1});;
            if(it != s.begin())
                it--;
            for(it; it != it2; it++)
            {
                long long l1 = it -> first, r1 = it -> second;
                if(l <= r1 && l1 <= r)
                    v.push_back({max(l, l1), min(r, r1)});
            }
            s.clear();
        }
        else
        {
            auto it = s.upper_bound({l, l}), it2 = s.upper_bound({r, hi + 1});;
            if(it != s.begin())
                it--;
            for(it; it != it2; it++)
            {
                long long l1 = it -> first, r1 = it -> second;
                if(l <= r1 && l1 <= r)
                {
                    long long l2 = max(l, l1), r2 = min(r, r1);
                    v1.push_back({l1, r1});
                    if(l1 < l2 && r2 < r1)
                    {
                        v.push_back({l1, l2 - 1});
                        v.push_back({r2 + 1, r1});
                    }
                    else if(r2 == r1 && l1 != l2)
                        v.push_back({l1, l2 - 1});
                    else if(l1 == l2 && r1 != r2)
                        v.push_back({r2 + 1, r1});
                }
            }
        }
        for(int j = 0; j < v1.size(); j++)
            s.erase(v1[j]);
        for(int j = 0; j < v.size(); j++)
            s.insert(v[j]);
    }
    long long ans = -1;
    if(s.empty())
    {
        cout << "Game cheated!";
        return 0;
    }
    else if(s.size() == 1)
    {
        auto it = s.begin();
        if(it -> first == it -> second)
        {
            cout << s.begin() -> first;
            return 0;
        }
    }
    cout << "Data not sufficient!";
    return 0;
}
Exemplo n.º 7
0
// divide and conquer algorithm of the sequencing
  void CompNovoIdentificationCID::getDecompositionsDAC_(set<String> & sequences, Size left, Size right, DoubleReal peptide_weight, const PeakSpectrum & CID_spec, Map<DoubleReal, CompNovoIonScoringCID::IonScore> & ion_scores)
  {
    static DoubleReal oxonium_mass = EmpiricalFormula("H2O+").getMonoWeight();
    DoubleReal offset_suffix(CID_spec[left].getPosition()[0] - oxonium_mass);
    DoubleReal offset_prefix(peptide_weight - CID_spec[right].getPosition()[0]);

#ifdef DAC_DEBUG
    static Int depth_(0);
    ++depth_;
    String tabs_(depth_, '\t');
    cerr << tabs_ << "void getDecompositionsDAC(sequences[" << sequences.size() << "], " << left << ", " << right << ") ";
    cerr << CID_spec[left].getPosition()[0] << " " << CID_spec[right].getPosition()[0] << " diff=";
#endif

    DoubleReal diff = CID_spec[right].getPosition()[0] - CID_spec[left].getPosition()[0];

#ifdef DAC_DEBUG
    cerr << diff << endl;
    cerr << "offset_prefix=" << offset_prefix << ", offset_suffix=" << offset_suffix << endl;
#endif

    if (subspec_to_sequences_.has(left) && subspec_to_sequences_[left].has(right))
    {
      sequences = subspec_to_sequences_[left][right];

#ifdef DAC_DEBUG
      depth_--;
      cerr << tabs_ << "from cache DAC: " << CID_spec[left].getPosition()[0] << " " << CID_spec[right].getPosition()[0] << " " << sequences.size() << " " << left << " " << right << endl;
#endif
      return;
    }

    // no further solutions possible?
    if (diff < min_aa_weight_)
    {
#ifdef DAC_DEBUG
      depth_--;
#endif
      return;
    }

    // no further division needed?
    if (diff <= max_decomp_weight_)
    {
      vector<MassDecomposition> decomps;

      // if we are at the C-terminus use precursor_mass_tolerance_
      if (offset_prefix < precursor_mass_tolerance_)
      {
        Param decomp_param(mass_decomp_algorithm_.getParameters());
        decomp_param.setValue("tolerance", precursor_mass_tolerance_);
        mass_decomp_algorithm_.setParameters(decomp_param);
        getDecompositions_(decomps, diff);
        decomp_param.setValue("tolerance", fragment_mass_tolerance_);
        mass_decomp_algorithm_.setParameters(decomp_param);
      }
      else
      {
        getDecompositions_(decomps, diff);
      }
      //filterDecomps_(decomps);

#ifdef DAC_DEBUG
      cerr << tabs_ << "Found " << decomps.size() << " decomps" << endl;
      cerr << tabs_ << "Permuting...";
#endif

      //static Map<String, set<String> > permute_cache;
      for (vector<MassDecomposition>::const_iterator it = decomps.begin(); it != decomps.end(); ++it)
      {
#ifdef DAC_DEBUG
        cerr << it->toString() << endl;
#endif

        String exp_string = it->toExpandedString();
        if (!permute_cache_.has(exp_string))
        {
          permute_("", exp_string, sequences);
          permute_cache_[exp_string] = sequences;
        }
        else
        {
          sequences = permute_cache_[exp_string];
        }
      }

#ifdef DAC_DEBUG
      cerr << tabs_ << CID_spec[left].getPosition()[0] << " " << CID_spec[right].getPosition()[0] << " " << peptide_weight << endl;
      if (sequences.size() > max_subscore_number_)
      {
        cerr << tabs_ << "Reducing #sequences from " << sequences.size() << " to " << max_subscore_number_ << "(prefix=" << offset_prefix  << ", suffix=" << offset_suffix << ")...";
      }
#endif

      // C-terminus
      if (offset_suffix <= precursor_mass_tolerance_)
      {
        filterPermuts_(sequences);
      }

      // reduce the sequences
      reducePermuts_(sequences, CID_spec, offset_prefix, offset_suffix);
#ifdef DAC_DEBUG
      cerr << "Writing to cache " << left << " " << right << endl;
#endif
      subspec_to_sequences_[left][right] = sequences;

#ifdef DAC_DEBUG
      cerr << "ended" << endl;
      cerr << tabs_ << "DAC: " << CID_spec[left].getPosition()[0] << " " << CID_spec[right].getPosition()[0] << " " << sequences.size() << endl;
      depth_--;
#endif

      return;
    }

    // select suitable pivot peaks
    vector<Size> pivots;

    if (offset_suffix < precursor_mass_tolerance_ && offset_prefix < precursor_mass_tolerance_)
    {
      selectPivotIons_(pivots, left, right, ion_scores, CID_spec, peptide_weight, true);
    }
    else
    {
      selectPivotIons_(pivots, left, right, ion_scores, CID_spec, peptide_weight, false);
    }

    // run divide step
#ifdef DAC_DEBUG
    cerr << tabs_ << "Selected " << pivots.size() << " pivot ions: ";
    for (vector<Size>::const_iterator it = pivots.begin(); it != pivots.end(); ++it)
    {
      cerr << *it << "(" << CID_spec[*it].getPosition()[0] << ") ";
    }
    cerr << endl;
#endif

    for (vector<Size>::const_iterator it = pivots.begin(); it != pivots.end(); ++it)
    {
      set<String> seq1, seq2, new_sequences;

      // the smaller the 'gap' the greater the chance of not finding anything
      // so we we compute the smaller gap first
      DoubleReal diff1(CID_spec[*it].getPosition()[0] - CID_spec[left].getPosition()[0]);
      DoubleReal diff2(CID_spec[right].getPosition()[0] - CID_spec[*it].getPosition()[0]);

      if (diff1 < diff2)
      {
        getDecompositionsDAC_(seq1, left, *it, peptide_weight, CID_spec, ion_scores);
        if (seq1.empty())
        {
#ifdef DAC_DEBUG
          cerr << tabs_ << "first call produced 0 candidates (" << diff1 << ")" << endl;
#endif
          continue;
        }

        getDecompositionsDAC_(seq2, *it, right, peptide_weight, CID_spec, ion_scores);
      }
      else
      {
        getDecompositionsDAC_(seq2, *it, right, peptide_weight, CID_spec, ion_scores);
        if (seq2.empty())
        {
#ifdef DAC_DEBUG
          cerr << tabs_ << "second call produced 0 candidates (" << diff2 << ")" << endl;
#endif
          continue;
        }

        getDecompositionsDAC_(seq1, left, *it, peptide_weight, CID_spec, ion_scores);
      }

#ifdef DAC_DEBUG
      cerr << tabs_ << "Found " << seq1.size() << " solutions (1) " << diff1 << endl;
      cerr << tabs_ << "Found " << seq2.size() << " solutions (2) " << diff2 << endl;
      cerr << tabs_ << "inserting " << seq1.size() * seq2.size()  << " sequences" << endl;
#endif

      // C-terminus
      if (offset_suffix <= fragment_mass_tolerance_)
      {
        filterPermuts_(seq1);
      }

      // test if we found enough sequence candidates
      if (seq1.empty() || seq2.empty())
      {
        continue;
      }

      for (set<String>::const_iterator it1 = seq1.begin(); it1 != seq1.end(); ++it1)
      {
        for (set<String>::const_iterator it2 = seq2.begin(); it2 != seq2.end(); ++it2)
        {
          new_sequences.insert(*it2 + *it1);
        }
      }

      if (seq1.size() * seq2.size() > max_subscore_number_ /* && (offset_prefix > fragment_mass_tolerance_ || offset_suffix > fragment_mass_tolerance_)*/)
      {
#ifdef DAC_DEBUG
        cerr << tabs_ << CID_spec[left].getPosition()[0] << " " << CID_spec[right].getPosition()[0] << " " << peptide_weight << endl;
        cerr << tabs_ << "Reducing #sequences from " << new_sequences.size() << " to " << max_subscore_number_ << "(prefix=" << offset_prefix  << ", suffix=" << offset_suffix << ")...";
#endif
        if (offset_prefix > precursor_mass_tolerance_ || offset_suffix > precursor_mass_tolerance_)
        {
          reducePermuts_(new_sequences, CID_spec, offset_prefix, offset_suffix);
        }

#ifdef DAC_DEBUG
        for (set<String>::const_iterator it1 = new_sequences.begin(); it1 != new_sequences.end(); ++it1)
        {
          cerr << tabs_ << *it1 << endl;
        }
        cerr << endl;
#endif
      }

      for (set<String>::const_iterator sit = new_sequences.begin(); sit != new_sequences.end(); ++sit)
      {
        sequences.insert(*sit);
      }
    }
#ifdef DAC_DEBUG
    cerr << tabs_ << "Found sequences for " << CID_spec[left].getPosition()[0] << " " << CID_spec[right].getPosition()[0] << endl;
    for (set<String>::const_iterator sit = sequences.begin(); sit != sequences.end(); ++sit)
    {
      cerr << tabs_ << *sit << endl;
    }
#endif

    // reduce the permuts once again to reduce complexity
    if (offset_prefix > precursor_mass_tolerance_ || offset_suffix > precursor_mass_tolerance_)
    {
      reducePermuts_(sequences, CID_spec, offset_prefix, offset_suffix);
    }

#ifdef DAC_DEBUG
    cerr << "Writing to cache " << left << " " << right << endl;
#endif

    subspec_to_sequences_[left][right] = sequences;

#ifdef DAC_DEBUG
    depth_--;
    cerr << tabs_ << "DAC: " << CID_spec[left].getPosition()[0] << " " << CID_spec[right].getPosition()[0] << " " << sequences.size() << endl;
#endif
    return;

  }
Exemplo n.º 8
0
chrono::microseconds algoritmo(unsigned int n, unsigned int m, unsigned int costoTotal, vector< list<Arista> > aristasDeCadaVertice, vector< list<Arista> > aristasDeCadaVerticeAGM, set<Arista, comparacionArista> aristasGrafo, set<Vertice> verticesAGM, set<Arista, comparacionArista> aristasAGM, set<Arista, comparacionArista> aristasCandidatasAGM, list<Arista> aristasAnillo) 
{
    auto start_time = chrono::high_resolution_clock::now();
    // Arranco poniendo el vértice 0 en verticesAGM, y sus aristas en aristasCandidatasAGM
    verticesAGM.insert(0);
    for(auto it = aristasDeCadaVertice[0].begin(); it != aristasDeCadaVertice[0].end(); it++) {
        aristasCandidatasAGM.insert(*it);
    }
    
    while (aristasAGM.size() < n - 1 && aristasCandidatasAGM.size() > 0 ) {
        auto iterAristaMinima = aristasCandidatasAGM.begin();
        Arista a = *iterAristaMinima;
        aristasCandidatasAGM.erase(iterAristaMinima);           
        pair<bool,Vertice> infoIncidencia = a.incideEnDosVertices(verticesAGM);
        if (infoIncidencia.first) {                             
            continue;
        } else {
            Vertice nuevo = infoIncidencia.second;              
            verticesAGM.insert(nuevo);                          
            aristasGrafo.erase(a);                              
            aristasAGM.insert(a);                               
            Vertice otro = a.dameElOtroVertice(nuevo);
            aristasDeCadaVerticeAGM[nuevo].push_back(a);        
            aristasDeCadaVerticeAGM[otro].push_back(a);
            for(auto it = aristasDeCadaVertice[nuevo].begin(); it != aristasDeCadaVertice[nuevo].end(); it++) {
                if (it->incideEnDosVertices(verticesAGM).first) {
                    continue;                                   
                }
                aristasCandidatasAGM.insert(*it);
            }
        }
    }
    
    if ( (aristasAGM.size() < n - 1) || (aristasGrafo.size() == 0)) {
        // No hay solucion
    } else {
        Arista menor = *aristasGrafo.begin();
        aristasAGM.insert(menor);
        for (auto it = aristasAGM.begin(); it != aristasAGM.end(); it++) {
            costoTotal += it->costo();
        }
        Vertice primero = menor.dameVerticeUno();
        Vertice segundo = menor.dameVerticeDos();
        aristasDeCadaVerticeAGM[primero].push_back(menor);
        aristasDeCadaVerticeAGM[segundo].push_back(menor);
        // Tengo que encontrar el circuito simple, esto es, el anillo
        infoVerticeDFS info[n];
        DFS_visit(aristasDeCadaVerticeAGM, info, primero);
        if (info[primero].backEdges.size() != 1) {
            cout << "Hay algo mal, el vertice deberia tener exactamente un back edge." << endl;
        }
        Arista backEdge = info[primero].backEdges.front();
        aristasAnillo.push_back(backEdge);
        aristasAGM.erase(backEdge);
        Vertice actual = backEdge.dameElOtroVertice(primero);
        while (actual != primero) {
            aristasAGM.erase(info[actual].aristaAnterior);
            aristasAnillo.push_back(info[actual].aristaAnterior);
            actual = info[actual].verticeAnterior;
        }
    }
    
    auto end_time = chrono::high_resolution_clock::now();
    chrono::microseconds tiempo = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
    return tiempo;
}
Exemplo n.º 9
0
void extend(vector<vector<char>> &a, list<set<int>> &REZULT, set <int> candidates, set <int> not, set <int> M){
	set <int> K, P;
	int v, SIZE = a[1].size();
	auto theIterator = candidates.begin();
	while ((candidates.size() != 0) && check(a, candidates, not)){
		K.clear();
		P.clear();
		for (auto it = not.begin(); it != not.end(); it++) { P.insert(*it); }
		for (auto it = candidates.begin(); it != candidates.end(); it++) { K.insert(*it); }
		v = *candidates.begin();
		M.insert(v);
		for (int i = 0; i < SIZE; i++)
		{
			if (!a[v][i])
			{
				theIterator = K.find(i);
				if (theIterator != K.end())
				{
					K.erase(theIterator);
				}
				theIterator = P.find(i);
				if (theIterator != P.end())
				{
					P.erase(theIterator);
				}
			}
		}
		theIterator = K.find(v);
		if (theIterator != K.end())
		{
			K.erase(theIterator);
		}
		if ((P.size() == 0) && (K.size() == 0))
		{
			REZULT.push_back(M);
			//if (REZULT.size()%100==0)
			//	cout << M.size() << " ";
			if (M.size() >= max_size){
				max_size = M.size();
				cout << M.size() << " ";
				show_clique(M, nv, nv);
			}
			if (M.size() >= CLIQUE_SIZE)
				stop_flag = 1;
		}
		else{
			if ((REZULT.size() < CLIQUES_COUNT) && (!stop_flag)){
			//if (!stop_flag){
				extend(a, REZULT, K, P, M);
			}
			else{
				break;
			}
		}
		theIterator = candidates.find(v);
		if (theIterator != candidates.end())
		{
			candidates.erase(theIterator);
		}
		theIterator = M.find(v);
		if (theIterator != M.end())
		{
			M.erase(theIterator);
		}
		not.insert(v);
	}
}
Exemplo n.º 10
0
int main()
{
 ios_base::sync_with_stdio(0);

 fill(rem_deg, 0);
 fill(xor_all, 0);
 fill(xor_done, 0);

 int n;

 cin>>n;

 for(int i=0;i<n;i++)
     {
          cin>>rem_deg[i]>>xor_all[i];

          if( rem_deg[i] > 0 )
              Q.insert( mp(rem_deg[i],i) );
     }

  while( sz(Q) )
  {
      pii top = *Q.begin();
                  Q.erase(Q.find(top));

      int curr_node = top.Y;
      int  rem_d = top.X;

      if( rem_d == 0)
        continue;

      assert( rem_d == 1 );

      int other = xor_all[curr_node] xor xor_done[curr_node];

      ans.pb( mp(curr_node,other));

     // cout<<curr_node<<"  "<<other<<endl;

      pii todel = mp( rem_deg[other] , other );
                  Q.erase( Q.find(todel) );

      rem_deg[curr_node]=0;
      rem_deg[other]--;


      xor_all[curr_node] =0;

      xor_all[other]= xor_all[other] xor curr_node;

      if(rem_deg[other] > 0 )
        Q.insert( mp( rem_deg[other] , other ) );
  }


  cout<<sz(ans)<<endl;


  for(int i=0;i<sz(ans);i++)
    cout<<ans[i].X<<" "<<ans[i].Y<<endl;

 return 0;

}
Exemplo n.º 11
0
void printset(set<unsigned int> &m){
	for(set<unsigned int>::iterator i = m.begin(); i != m.end(); i++)
		cout << *i << " ";
}
Exemplo n.º 12
0
int main( int argc, char* argv[ ] )
{
   bool has_object_path = false;
   string src_file_name, dependency_file_extension( "obj" );
   string object_file_path;

   if( argc < 2 || argc > 5 )
   {
      cout << c_title << '\n' << c_usage << endl;
      return 0;
   }

   int argnum = 1;
   while( argnum < argc - 1 )
   {
      string opt( argv[ argnum++ ] );
      if( opt.size( ) < 2
       || ( opt.substr( 0, 2 ) != "-i" && opt.substr( 0, 2 ) != "/i"
       && opt.substr( 0, 2 ) != "-o" && opt.substr( 0, 2 ) != "/o"
       && opt.substr( 0, 2 ) != "-x" && opt.substr( 0, 2 ) != "/x" ) )
      {
         cerr << "Error: Unknown option '" << opt << "'." << endl;
         return 1;
      }

      bool is_object_path = false;
      bool is_include_path = false;
      if( opt.substr( 0, 2 ) == "-o" || opt.substr( 0, 2 ) == "/o" )
         is_object_path = true;
      else if( opt.substr( 0, 2 ) == "-i" || opt.substr( 0, 2 ) == "/i" )
         is_include_path = true;

      opt.erase( 0, 2 );

      if( is_object_path )
      {
         object_file_path = opt;
         has_object_path = true;
         transform_path_separators( object_file_path );

         if( !object_file_path.empty( ) && object_file_path[ object_file_path.size( ) - 1 ] != '\\' )
            object_file_path += '\\';
      }
      else if( is_include_path )
      {
         size_t pos = opt.find( ';' );
         while( true )
         {
            include_paths.insert( opt.substr( 0, pos ) );
            if( pos == string::npos )
               break;

            opt.erase( 0, pos + 1 );
            pos = opt.find( ';' );
         }
      }
      else
         dependency_file_extension = opt;
   }

   src_file_name = argv[ argnum ];

   size_t pos = src_file_name.find_last_of( '.' );
   if( pos == string::npos )
   {
      cerr << "Error: Didn't find file extension in '" << src_file_name << "'." << endl;
      return 1;
   }

   string object_file( src_file_name.substr( 0, pos ) );

   if( has_object_path )
   {
      transform_path_separators( object_file );

      pos = object_file.find_last_of( '\\' );
      if( pos != string::npos )
         object_file.erase( 0, pos + 1 );

      object_file = object_file_path + object_file;
   }

   add_include_names( src_file_name );

   object_file = object_file + '.' + dependency_file_extension;
   cout << object_file << ":\\\n" << ' ' << src_file_name;

   set< string >::iterator i;
   for( i = include_names.begin( ); i != include_names.end( ); i++ )
      cout << "\\\n " << *i;

   cout << endl;

   return 0;
}
Exemplo n.º 13
0
void add_include_names( const string& file_name, bool is_root_file = true )
{
   string path;

   ifstream inpf( file_name.c_str( ) );

   if( is_root_file && !inpf )
   {
      cerr << "Error: Unable to open source file '" << file_name << "' for input." << endl;
      exit( 1 );
   }

   if( !is_root_file )
   {
      set< string >::iterator i;
      for( i = include_paths.begin( ); i != include_paths.end( ); ++i )
      {
         string str( *i );
         str += '\\';
         str += file_name;

         inpf.clear( );
         inpf.open( str.c_str( ), ios::in );
         if( inpf )
         {
            path = *i;
            break;
         }
      }

      if( !inpf )
      {
         cerr << "Error: Unable to open source file '" << file_name << "' for input." << endl;
         exit( 1 );
      }

      string str( path );
      if( !str.empty( ) )
         str += '\\';

      str += file_name;
      transform_path_separators( str );

      if( include_names.find( str ) != include_names.end( ) )
         return;

      include_names.insert( str );
      size_t pos = str.find_last_of( '\\' );
      if( pos != string::npos )
      {
         string current = str.substr( 0, pos );
         if( include_paths.find( current ) == include_paths.end( ) )
            include_paths.insert( current );
      }
   }

   string line, include;
   while( getline( inpf, line ) )
   {
      if( get_include_name( line, include ) )
         add_include_names( include, false );
   }
}
Exemplo n.º 14
0
int solve() {
    generateFolds();
    //bit rep of protein, 0: H, 1: P
    int sum = 0;
    concurrent_vector<int> maxBond;
    parallel_for(0, 1 << LEN,
        [&](int i) {
        int head = LEN - 1, tail = 0;
        int mirrorFactor = 1; //2 if mirror exists, 1 applies for HHHH, or PPPP
        while (head > tail) {
            bool h = i & (1 << head);
            bool t = i & (1 << tail);
            if (h == t) {
                //could be palindrome, then we can not rely on mirror
                tail++;
                head--;
            }
            else {
                //head != tail, a mirror exists
                if (h < t) {
                    //we will calculate this one, and skip the other mirrored string
                    mirrorFactor = 2;
                }
                else {
                    return; //skip
                }
                break;
            }
        }

        int maxNewBond = 0;
        int fixed = countExistingBond(i);
        int newBond;
        for (auto fold = allFolds.begin(); fold != allFolds.end(); fold++) {
            if (maxNewBond >= fold->size()) {
                break; //impossible to beat the current best
            }
            newBond = countNewBonds(i, *fold);
            maxNewBond = max(maxNewBond, newBond);
            if (newBond == fold->size()) {
                //all match, this is the best solution, because we search in order of number of new bonds
                break;
            }

        }
        maxBond.push_back((maxNewBond + fixed) * mirrorFactor);
    });
    sum = accumulate(maxBond.begin(), maxBond.end(), 0);
    /* replaced by parallel_for
    int nSkipped = 0;
    int nPal = 0;

    for (int i = 0; i < (1 << LEN); i++) {
        int head = LEN - 1, tail = 0;
        int mirrorFactor = 1; //2 if mirror exists, 1 applies for HHHH, or PPPP
        bool skip = false;
        while (head > tail) {
            bool h = i & (1 << head);
            bool t = i & (1 << tail);
            if (h == t) {
                //could be palindrome, then we can not rely on mirror
                tail++;
                head--;
            }
            else {
                //head != tail, a mirror exists
                if (h < t) {
                    //we will calculate this one, and skip the other mirrored string
                    mirrorFactor = 2;
                }
                else {
                    skip = true;
                    nSkipped++;
                }
                break;
            }
        }
        if (skip) {
            continue;
        }
        if (mirrorFactor == 1) {
            nPal++;
        }
        int maxNewBond = 0;
        int fixed = countExistingBond(i);
        int newBond;
        for (auto fold = allFolds.begin(); fold != allFolds.end(); fold++) {
            if (maxNewBond >= fold->size()) {
                break; //impossible to beat the current best
            }
            newBond = countNewBonds(i, *fold);
            maxNewBond = max(maxNewBond, newBond);
            if (newBond == fold->size()) {
                //all match, this is the best solution, because we search in order of number of new bonds
                break;
            }

        }

        sum += (maxNewBond + fixed) * mirrorFactor;
    }
    cout << "Skipped: " << nSkipped << endl;
    cout << "Palindrome: " << nPal << endl;
    */
    return sum;
}
Exemplo n.º 15
0
void print_dies(ostream &s, set<iterator_base> dies, optional<type_set&> types) {
	for (auto iter = dies.begin(); iter != dies.end(); iter++) {
		 print_type_die(s, *iter, types);
		 s << endl << endl;
	}
}
Exemplo n.º 16
0
    void drillDown( boost::filesystem::path root, bool use_db, bool use_coll, bool top_level=false ) {
        LOG(2) << "drillDown: " << root.string() << endl;

        // skip hidden files and directories
        if (root.leaf().string()[0] == '.' && root.leaf().string() != ".")
            return;

        if ( is_directory( root ) ) {
            boost::filesystem::directory_iterator end;
            boost::filesystem::directory_iterator i(root);
            while ( i != end ) {
                boost::filesystem::path p = *i;
                i++;

                if (use_db) {
                    if (boost::filesystem::is_directory(p)) {
                        error() << "ERROR: root directory must be a dump of a single database" << endl;
                        error() << "       when specifying a db name with --db" << endl;
                        printHelp(cout);
                        return;
                    }
                }

                if (use_coll) {
                    if (boost::filesystem::is_directory(p) || i != end) {
                        error() << "ERROR: root directory must be a dump of a single collection" << endl;
                        error() << "       when specifying a collection name with --collection" << endl;
                        printHelp(cout);
                        return;
                    }
                }

                // don't insert oplog
                if (top_level && !use_db && p.leaf() == "oplog.bson")
                    continue;

                // Only restore indexes from a corresponding .metadata.json file.
                if ( p.leaf() != "system.indexes.bson" ) {
                    drillDown(p, use_db, use_coll);
                }
            }

            return;
        }

        if ( endsWith( root.string().c_str() , ".metadata.json" ) ) {
            // Metadata files are handled when the corresponding .bson file is handled
            return;
        }

        if ( ! ( endsWith( root.string().c_str() , ".bson" ) ||
                 endsWith( root.string().c_str() , ".bin" ) ) ) {
            error() << "don't know what to do with file [" << root.string() << "]" << endl;
            return;
        }

        log() << root.string() << endl;

        if ( root.leaf() == "system.profile.bson" ) {
            log() << "\t skipping" << endl;
            return;
        }

        string ns;
        if (use_db) {
            ns += _db;
        }
        else {
            ns = root.parent_path().filename().string();
            if (ns.empty())
                ns = "test";
        }

        verify( ns.size() );

        string oldCollName = root.leaf().string(); // Name of the collection that was dumped from
        oldCollName = oldCollName.substr( 0 , oldCollName.find_last_of( "." ) );
        if (use_coll) {
            ns += "." + _coll;
        }
        else {
            ns += "." + oldCollName;
        }

        log() << "\tgoing into namespace [" << ns << "]" << endl;

        if ( _drop ) {
            if (root.leaf() != "system.users.bson" ) {
                log() << "\t dropping" << endl;
                conn().dropCollection( ns );
            } else {
                // Create map of the users currently in the DB
                BSONObj fields = BSON("user" << 1);
                scoped_ptr<DBClientCursor> cursor(conn().query(ns, Query(), 0, 0, &fields));
                while (cursor->more()) {
                    BSONObj user = cursor->next();
                    _users.insert(user["user"].String());
                }
            }
        }

        BSONObj metadataObject;
        if (_restoreOptions || _restoreIndexes) {
            boost::filesystem::path metadataFile = (root.branch_path() / (oldCollName + ".metadata.json"));
            if (!boost::filesystem::exists(metadataFile.string())) {
                // This is fine because dumps from before 2.1 won't have a metadata file, just print a warning.
                // System collections shouldn't have metadata so don't warn if that file is missing.
                if (!startsWith(metadataFile.leaf().string(), "system.")) {
                    log() << metadataFile.string() << " not found. Skipping." << endl;
                }
            } else {
                metadataObject = parseMetadataFile(metadataFile.string());
            }
        }

        _curns = ns.c_str();
        NamespaceString nss(_curns);
        _curdb = nss.db;
        _curcoll = nss.coll;

        // If drop is not used, warn if the collection exists.
        if (!_drop) {
            scoped_ptr<DBClientCursor> cursor(conn().query(_curdb + ".system.namespaces",
                                                            Query(BSON("name" << ns))));
            if (cursor->more()) {
                // collection already exists show warning
                warning() << "Restoring to " << ns << " without dropping. Restored data "
                             "will be inserted without raising errors; check your server log"
                             << endl;
            }
        }

        vector<BSONObj> indexes;
        if (_restoreIndexes && metadataObject.hasField("indexes")) {
            const vector<BSONElement> indexElements = metadataObject["indexes"].Array();
            for (vector<BSONElement>::const_iterator it = indexElements.begin(); it != indexElements.end(); ++it) {
                // Need to make sure the ns field gets updated to
                // the proper _curdb + _curns value, if we're
                // restoring to a different database.
                const BSONObj indexObj = renameIndexNs(it->Obj());
                indexes.push_back(indexObj);
            }
        }
        const BSONObj options = _restoreOptions && metadataObject.hasField("options") ?
                                metadataObject["options"].Obj() : BSONObj();

        if (_doBulkLoad) {
            RemoteLoader loader(conn(), _curdb, _curcoll, indexes, options);
            processFile( root );
            loader.commit();
        } else {
            // No bulk load. Create collection and indexes manually.
            if (!options.isEmpty()) {
                createCollectionWithOptions(options);
            }
            // Build indexes last - it's a little faster.
            processFile( root );
            for (vector<BSONObj>::iterator it = indexes.begin(); it != indexes.end(); ++it) {
                createIndex(*it);
            }
        }

        if (_drop && root.leaf() == "system.users.bson") {
            // Delete any users that used to exist but weren't in the dump file
            for (set<string>::iterator it = _users.begin(); it != _users.end(); ++it) {
                BSONObj userMatch = BSON("user" << *it);
                conn().remove(ns, Query(userMatch));
            }
            _users.clear();
        }
    }
Exemplo n.º 17
0
template <typename T, typename C> inline string DebugPrint(set<T, C> const & v)
{
  return ::my::impl::DebugPrintSequence(v.begin(), v.end());
}
Exemplo n.º 18
0
set<int> get_intersect(const set<int>& s1, const set<int>& s2) {
    set<int> intersect;
    set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),
                     std::inserter(intersect,intersect.begin()));
    return intersect;
}
Exemplo n.º 19
0
  void CompNovoIdentificationCID::reducePermuts_(set<String> & permuts, const PeakSpectrum & CID_spec, DoubleReal prefix, DoubleReal suffix)
  {
    if (permuts.size() < max_subscore_number_)
    {
      return;
    }

    vector<Permut> score_permuts;

    Size i(0);
    for (set<String>::const_iterator it = permuts.begin(); it != permuts.end(); ++it, ++i)
    {
#ifdef REDUCE_PERMUTS_DEBUG
      if (i % 1000 == 0)
      {
        cerr << (DoubleReal)i / permuts.size() * 100 << "%" << endl;
      }
#endif

      PeakSpectrum CID_sim_spec;
      getCIDSpectrumLight_(CID_sim_spec, *it, prefix, suffix);
      //getCIDSpectrum_(CID_sim_spec, *it, 1, prefix, suffix);

      DoubleReal score = zhang_(CID_sim_spec, CID_spec);

      if (boost::math::isnan(score))
      {
        score = 0;
      }

      score /= it->size();

      if (boost::math::isnan(score))
      {
        score = 0;
      }


#ifdef REDUCE_PERMUTS_DEBUG
      cerr << "Subscoring: " << *it << " " << cid_score << " (CID=";
/*      for (PeakSpectrum::ConstIterator pit = CID_sim_spec.begin(); pit != CID_sim_spec.end(); ++pit)
        {
        cerr << pit->getPosition()[0] << "|" << pit->getIntensity() << "; ";
        }*/
      cerr << endl;
#endif

      Permut new_permut(it, score);
      score_permuts.push_back(new_permut);
    }

    sort(score_permuts.begin(), score_permuts.end(), Internal::PermutScoreComparator);

    set<String> new_permuts;
    Size count(0);
    for (vector<Permut>::const_iterator it = score_permuts.begin(); it != score_permuts.end() && count < max_subscore_number_; ++it, ++count)
    {
      new_permuts.insert(*it->getPermut());
#ifdef REDUCE_PERMUTS_DEBUG
      cerr << "Subscore winner: " << it->getPermut() << " " << it->getScore() << endl;
#endif
    }

    permuts = new_permuts;
    return;
  }
Exemplo n.º 20
0
static LRESULT CALLBACK GraphicsWindow_WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	CHECKPOINT_M( ssprintf("%p, %u, %08x, %08x", hWnd, msg, wParam, lParam) );

	/* Suppress autorun. */
	if( msg == g_iQueryCancelAutoPlayMessage )
		return true;

	switch( msg )
	{
	case WM_ACTIVATE:
	{
		const bool bInactive = (LOWORD(wParam) == WA_INACTIVE);
		const bool bMinimized = (HIWORD(wParam) != 0);
		const bool bHadFocus = g_bHasFocus;
		g_bHasFocus = !bInactive && !bMinimized;
		LOG->Trace( "WM_ACTIVATE (%i, %i): %s", bInactive, bMinimized, g_bHasFocus? "has focus":"doesn't have focus" );
		if( !g_bHasFocus )
		{
			RString sName = GetNewWindow();
			static set<RString> sLostFocusTo;
			sLostFocusTo.insert( sName );
			RString sStr;
			for( set<RString>::const_iterator it = sLostFocusTo.begin(); it != sLostFocusTo.end(); ++it )
				sStr += (sStr.size()?", ":"") + *it;

			LOG->MapLog( "LOST_FOCUS", "Lost focus to: %s", sStr.c_str() );
		}

		if( !g_bD3D && !g_CurrentParams.windowed && !g_bRecreatingVideoMode )
		{
			/* In OpenGL (not D3D), it's our job to unset and reset the full-screen video mode
			 * when we focus changes, and to hide and show the window.  Hiding is done in WM_KILLFOCUS,
			 * because that's where most other apps seem to do it. */
			if( g_bHasFocus && !bHadFocus )
			{
				ChangeDisplaySettings( &g_FullScreenDevMode, CDS_FULLSCREEN );
				ShowWindow( g_hWndMain, SW_SHOWNORMAL );
			}
			else if( !g_bHasFocus && bHadFocus )
			{
				ChangeDisplaySettings( NULL, 0 );
			}
		}

		return 0;
	}
	case WM_KILLFOCUS:
		if( !g_bD3D && !g_CurrentParams.windowed && !g_bRecreatingVideoMode )
			ShowWindow( g_hWndMain, SW_SHOWMINNOACTIVE );
		break;

	/* Is there any reason we should care what size the user resizes the window to? */
//	case WM_GETMINMAXINFO:

	case WM_SETCURSOR:
		if( !g_CurrentParams.windowed )
		{
			SetCursor( NULL );
			return 1;
		}
		break;

	case WM_SYSCOMMAND:
		switch( wParam&0xFFF0 )
		{
		case SC_MONITORPOWER:
		case SC_SCREENSAVE:
			return 0;
		}
		break;

	case WM_POWERBROADCAST:
		if(wParam==PBT_APMPOWERSTATUSCHANGE) {
			SYSTEM_POWER_STATUS powerstatus;
			GetSystemPowerStatus(&powerstatus);
			Message msg("PowerSupplyChange");
			switch(powerstatus.ACLineStatus) {
				case 0:
					msg.SetParam( "Online",false);
				break;

				case 1:
					msg.SetParam( "Online",true);
				break;

				default:
				case 255:
					msg.SetParam( "Online",false);
				break;
			}

			if(powerstatus.BatteryFlag & 8) {
				msg.SetParam( "Charging", true);
			} else {
				msg.SetParam( "Charging", false);
			}

			msg.SetParam( "BatteryExists", (powerstatus.BatteryFlag & 128) != 128);

			msg.SetParam( "BatteryCharge", (int)powerstatus.BatteryLifePercent);
			msg.SetParam( "BatteryLifetime", (int)powerstatus.BatteryLifeTime);
			msg.SetParam( "BatteryFullLifetime", (int)powerstatus.BatteryFullLifeTime);

			MESSAGEMAN->Broadcast( msg );
		}
		break;

	case WM_PAINT:
	{
		PAINTSTRUCT ps;
		BeginPaint( hWnd, &ps );
		EndPaint( hWnd, &ps );
		break;
	}

	case WM_KEYDOWN:
	case WM_KEYUP:
	case WM_SYSKEYDOWN:
	case WM_SYSKEYUP:
		/* We handle all input ourself, via DirectInput. */
		return 0;

	case WM_CLOSE:
		LOG->Trace("WM_CLOSE: shutting down");
		ArchHooks::SetUserQuit();
		return 0;

	case WM_WINDOWPOSCHANGED:
	{
		/* If we're fullscreen and don't have focus, our window is hidden, so GetClientRect
		 * isn't meaningful. */
		if( !g_CurrentParams.windowed && !g_bHasFocus )
			break;

		RECT rect;
		GetClientRect( hWnd, &rect );

		int iWidth = rect.right - rect.left;
		int iHeight = rect.bottom - rect.top;
		if( g_CurrentParams.width != iWidth || g_CurrentParams.height != iHeight )
		{
			g_CurrentParams.width = iWidth;
			g_CurrentParams.height = iHeight;
			g_bResolutionChanged = true;
		}
		break;
	}
	}

	CHECKPOINT_M( ssprintf("%p, %u, %08x, %08x", hWnd, msg, wParam, lParam) );

	if( m_bWideWindowClass )
		return DefWindowProcW( hWnd, msg, wParam, lParam );
	else
		return DefWindowProcA( hWnd, msg, wParam, lParam );
}
Exemplo n.º 21
0
/**
This function returns the union of two sets.
@param a is a set of ints.
@param b is a set of ints.

@return result is the set with the union of a and b.

*/
set<int> SetUnion(set<int> a, set<int> b){
	set<int> result(a);
	result.insert(b.begin(), b.end());

	return result;
}
 iterator begin() {
     return inner_set_.begin();
 }
Exemplo n.º 23
0
int main(int argc, char **argv) {

    stringstream nullStream;
    nullStream.clear(ios::failbit);

    const char *dev = NULL;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle;

    struct bpf_program fp;
    bpf_u_int32 mask;
    bpf_u_int32 net;

    bool source = false;
    bool replay = false;
    bool diaglog = false;
    const char *file = 0;

    vector< const char * > args;
    for( int i = 1; i < argc; ++i )
        args.push_back( argv[ i ] );

    try {
        for( unsigned i = 0; i < args.size(); ++i ) {
            const char *arg = args[ i ];
            if ( arg == string( "--help" ) ) {
                usage();
                return 0;
            }
            else if ( arg == string( "--forward" ) ) {
                forwardAddress = args[ ++i ];
            }
            else if ( arg == string( "--source" ) ) {
                uassert( 10266 ,  "can't use --source twice" , source == false );
                uassert( 10267 ,  "source needs more args" , args.size() > i + 2);
                source = true;
                replay = ( args[ ++i ] == string( "FILE" ) );
                diaglog = ( args[ i ] == string( "DIAGLOG" ) );
                if ( replay || diaglog )
                    file = args[ ++i ];
                else
                    dev = args[ ++i ];
            }
            else if ( arg == string( "--objcheck" ) ) {
                objcheck = true;
                outPtr = &nullStream;
            }
            else {
                serverPorts.insert( atoi( args[ i ] ) );
            }
        }
    }
    catch ( ... ) {
        usage();
        return -1;
    }

    if ( !serverPorts.size() )
        serverPorts.insert( 27017 );

    if ( diaglog ) {
        processDiagLog( file );
        return 0;
    }
    else if ( replay ) {
        handle = pcap_open_offline(file, errbuf);
        if ( ! handle ) {
            cerr << "error opening capture file!" << endl;
            return -1;
        }
    }
    else {
        if ( !dev ) {
            dev = pcap_lookupdev(errbuf);
            if ( ! dev ) {
                cerr << "error finding device: " << errbuf << endl;
                return -1;
            }
            cout << "found device: " << dev << endl;
        }
        if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
            cerr << "can't get netmask: " << errbuf << endl;
            return -1;
        }
        handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
        if ( ! handle ) {
            cerr << "error opening device: " << errbuf << endl;
            return -1;
        }
    }

    switch ( pcap_datalink( handle ) ) {
    case DLT_EN10MB:
        captureHeaderSize = 14;
        break;
    case DLT_NULL:
        captureHeaderSize = 4;
        break;
    default:
        cerr << "don't know how to handle datalink type: " << pcap_datalink( handle ) << endl;
    }

    assert( pcap_compile(handle, &fp, const_cast< char * >( "tcp" ) , 0, net) != -1 );
    assert( pcap_setfilter(handle, &fp) != -1 );

    cout << "sniffing... ";
    for ( set<int>::iterator i = serverPorts.begin(); i != serverPorts.end(); i++ )
        cout << *i << " ";
    cout << endl;

    pcap_loop(handle, 0 , got_packet, NULL);

    pcap_freecode(&fp);
    pcap_close(handle);

    return 0;
}
 const_iterator begin() const {
     return inner_set_.begin();
 }
Exemplo n.º 25
0
template <class T> T nth(const set<T> &s, int x) {
  typename set<T>::iterator answer(s.begin());
  for (int i(0); i < x; ++i) ++answer;
  return *answer;
}
void Solve()
{                              	
	int x;
	for (int i = 0; i < n; i++)
	{
		scanf ("%d", &x);
		if (mp.find(x) == mp.end())
		{
			mp[x] = 1;
			v.push_back(x);
		}
		else
			mp[x]++;
	}

	for (int i = 0; i < (int)v.size(); i++)
	{
		x = v[i];
		mn_st.insert(make_pair (mp[x], x));
		mx_st.insert(make_pair (-mp[x], x));	
	}

	pair <int, int> p;

	while ((int)mn_st.size() > 2)
	{
		v.clear();
		tmp.clear();
		p = (*mn_st.begin());
		mn_st.erase (p);
		mx_st.erase (make_pair (-p.first, p.second));
		tmp.push_back(p);

		p = (*mx_st.begin());
		p.first *= -1;
		mn_st.erase (p);
		mx_st.erase (make_pair (-p.first, p.second));
		tmp.push_back(p);
		p = (*mx_st.begin());
		p.first *= -1;
		mn_st.erase (p);
		mx_st.erase (make_pair (-p.first, p.second));
		tmp.push_back(p);
		for (int i = 0; i < 3; i++)
		{
			v.push_back(tmp[i].second);
			tmp[i].first--;
			if (tmp[i].first > 0)
			{
				mn_st.insert (tmp[i]);
				mx_st.insert (make_pair (-tmp[i].first, tmp[i].second));
			}
		}
		sort (v.begin(), v.end());
		ans_v.push_back(v);
	}

	printf ("%d\n", (int)ans_v.size());
 	for (int i = 0; i < (int)ans_v.size(); i++)
 		printf ("%d %d %d\n", ans_v[i][2], ans_v[i][1], ans_v[i][0]);
}
Exemplo n.º 27
0
Arquivo: 2.cpp Projeto: wolf-ik/aisd
int main() {
    scanf("%d", &T);
    //cin >> T;
    for (int test = 0; test < T; test++) {
        scanf("%d %d", &n, &m);
        //cin >> n >> m;
        for (int i = 0; i <= n + 1; i++) {
            for (int j = 0; j <= m + 1; j++) {
                if ((i >= 1) && (i <= n) && (j >= 1) && (j <= m)) {
                    scanf("%d", &a[i][j]);
                    //cin >> a[i][j];
                    f[i][j] = false;
                    ss.insert(a[i][j]);
                    g[a[i][j]].push_back(make_pair(i, j));
                } else {
                    a[i][j] = -1;
                    f[i][j] = false;
                }
            }
        }
        ans = 0;
        int h = *ss.begin();
        ss.erase(ss.begin());
        int     hh;
        while (!ss.empty()) {
            hh = *ss.begin();
            ss.erase(ss.begin());
            int dif = hh - h;
            ans += g[h].size() * dif;
            nex.clear();

            for (vector<pair<int,int> >::iterator ii = g[h].begin(); ii != g[h].end(); ii++) {
                int i = ii->first;
                int j = ii->second;
                ff = false;
                c.clear();
                if (!f[i][j]) dfs(i, j, h);
                for (vector<pair<int,int> >::iterator k = c.begin(); k != c.end(); k++) {
                    if (ff) {
                        a[k->first][k->second] = -1;
                        ans -= dif;
                    } else {
                        nex.push_back(make_pair(k->first, k->second));
                    }
                }
            }
            for (vector<pair<int,int> >::iterator i = nex.begin(); i != nex.end(); i++) {
                g[hh].push_back(make_pair(i->first, i->second));
                f[i->first][i->second] = false;
                a[i->first][i->second] = hh;
            }
            g[h].clear();
            h = hh;
        }
        g[h].clear();
        printf("%d\n", ans);
        //cout << ans << endl;
    }

    return 0;
}
Exemplo n.º 28
0
void drawSquares1( IplImage* img, CvSeq* squares )
{
    CvSeqReader reader;
    IplImage* cpy = cvCloneImage( img );
    int i,cnt = 0;
    cvStartReadSeq( squares, &reader, 0 );




    cout<<"**********Green Rectangle : "<<squares->total/4<<endl;
    // read 4 sequence elements at a time (all vertices of a square)
    for( i = 0; i < squares->total; i += 4 )
    {
        CvPoint pt[4],dis[4][4][15], *rect = pt;
        int count = 4;
        int tmpx = 0,tmpy = 0;
        bool flag = 0;
        // read 4 vertices
        CV_READ_SEQ_ELEM( pt[0], reader );
        CV_READ_SEQ_ELEM( pt[1], reader );
        CV_READ_SEQ_ELEM( pt[2], reader );
        CV_READ_SEQ_ELEM( pt[3], reader );

        set<CvPoint>::iterator it;
        for (it = vertx1.begin();it!=vertx1.end();it++){
            if(pointsDistance(pt[0],*it)<=dist)flag =1;
        }
        for (it = vertx2.begin();it!=vertx2.end();it++){
            if(pointsDistance(pt[0],*it)<=dist)flag =1;
        }
        for (it = vertx3.begin();it!=vertx3.end();it++){
            if(pointsDistance(pt[0],*it)<=dist)flag =1;
        }
        for (it = vertx4.begin();it!=vertx4.end();it++){
            if(pointsDistance(pt[0],*it)<=dist)flag =1;
        }



        if(vertx1.find(pt[0])==vertx1.end()||vertx2.find(pt[1])==vertx2.end()||vertx3.find(pt[2])==vertx3.end()||vertx4.find(pt[3])==vertx4.end())
        {

            vertx1.insert(pt[0]);
            vertx2.insert(pt[1]);
            vertx3.insert(pt[2]);
            vertx4.insert(pt[3]);

        }
        else flag = 1,cnt++;

        // draw the square as a closed polyline
        if(flag ==0)cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(255,0,0), 2, CV_AA, 0 );
        if(flag ==0){
            for (int i=0;i<4;i++){
                tmpx+= pt[i].x;
                tmpy+= pt[i].y;
                cout<<"@ "<<i<<" Point : "<<pt[i].x <<" "<<pt[i].y<<endl;
            }
            cout<<"$ Average : "<<tmpx/4<<" "<<tmpy/4<<endl<<endl;
        }


    }
    cout<<"----------------"<<squares->total/4-cnt<<"----------------"<<endl;


    cvShowImage( "Greeen", cpy );
    cvReleaseImage( &cpy );
}
Exemplo n.º 29
0
BOOL CFunctionListDlg::ReloadList ()
  {

  m_ctlFunctions.DeleteAllItems ();

  m_strFilter.MakeLower ();
  m_strFilter.TrimLeft ();
  m_strFilter.TrimRight ();

  // filter based on a partial match on what is in the filter box
  // (eg. "chat" would find all chat functions)

  CString strFunction;

  int nItem = 0;

  for (int i = 0; sFunctions [i] [0]; i++)
    {
    strFunction = sFunctions [i];
    strFunction.MakeLower ();

    if (m_strFilter.IsEmpty () || strFunction.Find (m_strFilter) != -1)
      {
      m_ctlFunctions.InsertItem (nItem, sFunctions [i]);

      // select the exact match, if any (so, if they highlight world.Note then it is selected)

      if (strFunction == m_strFilter)
        m_ctlFunctions.SetItemState (nItem, 
                                      LVIS_FOCUSED | LVIS_SELECTED,
                                      LVIS_FOCUSED | LVIS_SELECTED);
      nItem++;

      }
    }

  // add Lua functions
  if (m_bLua)
    {
    for (set<string>::const_iterator it = LuaFunctionsSet.begin ();
         it != LuaFunctionsSet.end (); 
         it++)

       {
        strFunction = it->c_str ();
        strFunction.MakeLower ();

        if (m_strFilter.IsEmpty () || strFunction.Find (m_strFilter) != -1)
          {
          m_ctlFunctions.InsertItem (nItem, it->c_str ());

          // select the exact match, if any (so, if they highlight world.Note then it is selected)

          if (strFunction == m_strFilter)
            m_ctlFunctions.SetItemState (nItem, 
                                          LVIS_FOCUSED | LVIS_SELECTED,
                                          LVIS_FOCUSED | LVIS_SELECTED);
          nItem++;

          }
           
       }   // end of doing each Lua function
    }


  // if the filtering results in a single item, select it
  if (nItem == 1)
    {
    m_ctlFunctions.SetItemState (0, 
                                  LVIS_FOCUSED | LVIS_SELECTED,
                                  LVIS_FOCUSED | LVIS_SELECTED);
    return FALSE;
    }

  if (m_strFilter.IsEmpty ())
    {
    m_ctlFilter.SetFocus ();
    return FALSE;
    }

  return TRUE;

  } // end of CFunctionListDlg::ReloadList
Exemplo n.º 30
0
void printset(set<int> &a)
{
    for(auto it=a.begin(); it !=a.end(); it++)
      cout<<*it<<",";  
  cout<<"\n";
}