Example #1
0
int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n, m, i = 0; 
	while(cin >> n){
		v.clear();
		inc.clear();
		topo.clear();
		order.clear();
		string line, line2;
		while(n--){ //read all nodes
			cin >> line;
			v[line];
			inc[line] = 0;
			order[line] = n;
		}
		cin >> m;
		while(m--){  //read vertex
			cin >> line >> line2;
			v[line].push_back(line2);
			++inc[line2];
		}
		topo_sort();
		//prints answer
		cout << "Case #" << ++i << ": Dilbert should drink beverages in this order:";
		for(auto &a: topo) cout << " " << a;
		cout << ".\n\n";
	}
	return 0;
}
int main(){
    string input;
    while(cin>>input){
        char c1 = input[0], c2 = input[2];
        adjacency[c1].push_back(c2);
    }
    for(int i = 65; i < 91; i++){
        to_print = false;
        complete.clear();
        visited.clear();
        char terminal = ';';

        char start = i;
        if(!visited[start]){
            if(cycle_found(start)&&to_print){
                incycle.push_back(start);
                //cout<<start<<' ';
                break;
            }
        }
    }
    sort(incycle.begin(), incycle.end());
    for(int i = 0; i < incycle.size(); i++){
        cout<<incycle[i]<<' ';
    }

}
Example #3
0
int main(){
	cout << setprecision(6)<<fixed;
	int t;

	cin >> t;
	set<int> s;
	map<int, int> convert;
	
	
	while(t--){
		dm.clear();
		dc.clear();
		s.clear();
		convert.clear();
		cin >> n;
		double f, fa;
		for(int k=0;k<n;k++){
			f=(double)k/(double)(n-1.0);
			fa=f;
			alpha[k]=0;
			for(int i=0;i<1000;i++){
				alpha[k] +=fa;
				fa *=f;
			}
		}

		for(int k=0;k<(n*n);k++){
			f=(double)k/(double)((n*n));
			fa=f;
			beta[k]=0;
			for(int i=0;i<1000;i++){
				beta[k] +=fa;
				fa *=f;
			}
		}
		for(int i=0;i<n;i++){
			cin >> a[i];
			s.insert(a[i]);
		}
		int p = 0;
		for(auto k: s){
			if(convert.find(k) == convert.end()){
				convert[k] = p;
			}
			p++;
		}
		int m=0;
		for(int i=0;i<n;i++){
			a[i] = convert[a[i]];
			m = setm(m,i,a[i]);
		}


		cout<<"Monty "<<M(m)<<" Carlos "<<C(m)<<endl;
		
	}
	
	
}
void solve(int start, string &s, vector<string> &words)
{
	//m stores info, m1 stores current info
	unordered_map<string, int>::iterator it;
	int p1 = start, p2 = start, len = words[0].length(), cur = 0;
	m1.clear();
	while(p2 + len - 1 < s.length())
	{
		while(cur != m.size() && p2 + len - 1 < s.length())
		{
			string tmp = s.substr(p2, len);
			it = m.find(tmp);
			if(it == m.end())
			{
				p2 += len;
				p1 = p2;
				cur = 0;
				m1.clear();
				continue;
			}
			else if(it->second == m1[tmp])
			{
			    string tmp2 = "";
			    while(p1 != p2 && tmp2 != tmp)
			    {
			        tmp2 = s.substr(p1, len);
			        if(m1.find(tmp2) != m1.end())
			        {
			            if(m1[tmp2] == m[tmp2])
			                cur--;
			            m1[tmp2]--;
			        }
			        p1 += len;
			    }
			    continue;
			}
			m1[tmp]++;
			if(it->second == m1[tmp])
				cur++;
			p2 += len;
		}
		while(cur == m.size() && p1 <= p2)
		{
			ans.push_back(p1);
			string tmp = s.substr(p1, len);
			it = m1.find(tmp);
			if(it == m1.end())
			{
				p1 += len;
				continue;
			}
			it->second--;
			if(it->second < m[tmp])
				cur--;
			p1 += len;
		}
	}
}
Example #5
0
        int maxPathSum(TreeNode *root){
            if(root == NULL)
                return 0;
            pathSum.clear();
            nodeSum.clear();

            dfs(root);
            return dfsMax(root);
        }
Example #6
0
void gao_TF_IDF(char * dim_items_txt){
    fstream item_values_file(dim_items_txt);              // for item's value
    int tot = 0, now = 0;
    // get item's value vector --------
    LL item, cat; string values_string;
    double st = clock();
    while(item_values_file >> item >> cat >> values_string){
        assert(item < M);
        if (now++ % SHOW == 0)
            cerr<<"now:\t"<<now<<"\titem:\t"<<item<<"\tcat\t"<<cat<<"\tvs\t"<<values_string<<endl;
        vector<LL> values;
        stringstream ss(values_string);
        LL val; char douhao;
        while(ss >> val){
            ss >> douhao;
            assert(douhao == ',' || douhao == '\n');
            values.push_back(val);
            item_value_times[item][val]++;
        }

        if ((now - 1) % SHOW == 0){ for (int i = 0; i < values.size(); i++) cerr<<" "<<values[i]; cerr<<"\n"; }

        sort(values.begin(), values.end());
        //values.erase(unique(values.begin(), values.end()), values.end());
        int sz = unique(values.begin(), values.end()) - values.begin();
        for (int i = 0; i < sz; i++){ // must unique for idf
            value_times[values[i]]++;
        }
        item_values[item] = values;
        item_cat[item]    = cat;
        cat_items[cat].push_back(item);
        tot++;
    }
    now = 0;
    for (unordered_map<LL, vector<LL> >::iterator it = item_values.begin(); it != item_values.end(); it++){
        LL item = it->first;
        vector<LL> & v = it->second;
        if (now++ % SHOW == 0)
            cerr<<"now:\t"<<now<<"\titem:\t"<<item<<"\tvaluesize:\t"<<v.size()<<endl;
        vector<PDL> res;
        sort(v.begin(), v.end());
        int sz = unique(v.begin(), v.end()) - v.begin();
        int words = v.size();
        for (int i = 0; i < sz; i++){
            LL val = v[i];
            double tf = item_value_times[item][val] * 1.0 / words;
            double idf = log(tot * 1.0 / (1 + value_times[val]));
            res.push_back(PDL(tf * idf, val));
            if ((now - 1) % SHOW == 0) { cerr<<"tf-idf = "<<tf*idf<<"\tval = "<<val<<endl; }
        }
        item_vector[item] = res;
        item_vector_len[item] = len(res);
    }
    cout<<"get item's vector over, time use:\t"<<(clock() - st) / CLOCKS_PER_SEC<<"\n";
    item_value_times.clear();
    value_times.clear();
}
Example #7
0
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
		if (node == NULL) return NULL;
        dfs(node);
		visit.clear();
		dfs2(node);
		visit.clear();
		UndirectedGraphNode * result = node->neighbors[(int)node->neighbors.size() - 1];
		dfs3(node);
		return result;
    }
Example #8
0
 bool canCross(vector<int> &stones) {
     if (stones.size() == 1)
         return true;
     if (stones[1] - stones[0] != 1)
         return false;
     s.clear(), m.clear();
     for (int i = 0; i < stones.size(); i++)
         s[stones[i]] = i;
     return helper(stones, 1, 1);
 }
 /** Initialize your data structure here. */
 AllOne() 
 {
     Str2Num.clear();
     Num2Strs.clear();
     Num2Iter.clear();
     ListNum.clear();     
     
     ListNum.push_back(0);
     Num2Iter[0] = ListNum.begin();
 }
Example #10
0
void StatsSender::SendStats(unordered_map<unsigned int, unsigned __int64> pickedItems, unordered_map<int, int> timers){

	_pickedItems = pickedItems;
	_timers = timers;


	pickedItems.clear();
	timers.clear();

	HANDLE h = CreateThread(NULL, 0, StaticThreadStart2, (void*) this, 0, 0);
}
Example #11
0
int main()
{
	int tests;
	int citiesN;
	int relationsN;
	int paths;
	string name;
	cin >> tests;

	for (int t = 0; t < tests; t++)
	{
		cityId.clear();
		graph.clear();
		cin >> citiesN;
		for(int c = 1; c <= citiesN; c++)
		{
			distances[c] = infinity;
			emptyDistances[c] = infinity;

			city city;
			cin >> city.name;
			graph[c] = city;
			cityId[city.name] = c;
			cin >> relationsN;

			for(int r = 0; r < relationsN; r++)
			{
				way way1;
				cin >> way1.destination >> way1.cost;
				graph[c].adjacent.push_back(way1);
				way way2 = way1;
				way2.destination = c;
				graph[way2.destination].adjacent.push_back(way2);
			}

		}

		cin >> paths;

		for (int p = 0; p < paths; p++)
		{
			string source, destination;
			cin >> source >> destination;
			distances = emptyDistances;
			fill(visited.begin(), visited.end(), false);
			dijkstra(cityId[source], cityId[destination]);
			cout << distances[cityId[destination]] << endl;
		}
	}
	
	return 0;
}
Example #12
0
int main()
{
//	freopen("in.txt","r",stdin);
	string name,party,club;
	char ins[100],*ptr;
	int TC,tmp,ans;
	TC = atoi(gets(ins));
	gets(ins);
	while(TC--)
	{
		name_set.clear(); party_set.clear(); club_set.clear();
		memset(graph,0,sizeof(graph));
		N = 1;
		while(gets(ins) && strlen(ins))
		{
			ptr = strtok(ins," ");
			name = string(ptr);
			ptr = strtok(NULL," ");
			party = string(ptr);
			graph[get(name_set,name)][get(party_set,party)] = 1;
			while(ptr = strtok(NULL," "))
			{
				club = string(ptr);
				graph[source()][get(club_set,club)] = 1;
				graph[get(club_set,club)][get(name_set,name)] = 1;
			}
		}
		tmp = (club_set.size() - 1) / 2;
		for(unordered_map<string,int>::iterator it = party_set.begin();it != party_set.end();it++)
			graph[it->second][target()] = tmp;
		ans = 0;
		visited.reset();
		while(tmp = maxflow(source(),INT_MAX))
		{
			ans += tmp;
			visited.reset();
		}
		if(ans != club_set.size())	printf("Impossible.\n");
		else
			for(unordered_map<string,int>::iterator it_name = name_set.begin();it_name != name_set.end();it_name++)
			for(unordered_map<string,int>::iterator it_club = club_set.begin();it_club != club_set.end();it_club++)
				if(graph[it_name->second][it_club->second])
				{
					printf("%s %s\n",(it_name->first).c_str(),(it_club->first).c_str());
					break;
				}
		if(TC)	printf("\n");
	}

	return 0;
}
Example #13
0
int main()
{
    ios_base::sync_with_stdio(false);

    bool first = true;
    int n;
    while (cin >> n)
    {
        if (first)  first = false;
        else    cout << '\n';

        Buys buy_orders(buy_cmp);
        Sells sell_orders(sell_cmp);
        for (auto i = 1; i <= n; ++i)
        {
            string cmd; cin >> cmd;
            if (cmd[0] == 'B')
                process_incoming(buy_orders, sell_orders, i);
            else if (cmd[0] == 'S')
                process_incoming(sell_orders, buy_orders, i);
            else // cancel order
            {
                int ci; cin >> ci;
                if (!gone.count(ci))
                {
                    if (b_seq2iter.count(ci))
                    {
                        auto &it = b_seq2iter[ci];
                        price2size[it->price] -= it->size;
                        buy_orders.erase(it);
                    }
                    else
                    {
                        auto &it = s_seq2iter[ci];
                        price2size[it->price] -= it->size;
                        sell_orders.erase(it);
                    }
                    gone.insert(ci);
                }
            }
            print_quote(buy_orders, sell_orders);
        }
        price2size.clear();
        b_seq2iter.clear();
        s_seq2iter.clear();
        gone.clear();
    }

    return 0;
}
Example #14
0
    int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
        int n = graph.size(); 
        parent.clear();
        count.clear();   
        for(int i = 0; i < n; ++i) {
            parent[i] = i; count[i] = 1;
        }
        vector<int> visited(n, false);

        for(int i = 0; i < n; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                if(graph[i][j])
                {
                    int pi = findParent(i);
                    int pj = findParent(j);
                    if(pi != pj)
                    {
                        parent[pi] = pj;
                        count[pj] += count[pi];
                    }
                }
            }
        }

        sort(initial.begin(), initial.end());
        map<int, vector<int>> m;
        for(int i : initial)
        {
            m[findParent(i)].push_back(i);
        }

        int minCount = 0;
        int minIdx = initial[0];

        for(const auto& p : m)
        {
            if(p.second.size() == 1)
            {
                if(count[p.first] > minCount)
                {
                    minCount = count[p.first];
                    minIdx = p.second[0];
                }
            }
        }
        return minIdx;
    }
/* 
 * Main method to call the prefix generation
 * @Params A - Vector of strings
 */
vector<string> Solution::prefix(vector<string> &A) {
    // create a empty vector for results
    vector<string> result;
    
    // clear the global hashmap
    res.clear();
    
    // return empty vector in case A is empty
    if(A.size() == 0) return result;
    
    // Generate the prefix tree
    Node* Tree = new Node("*");
    for(int i = 0; i < A.size(); i++) {
        Tree->insertChild(A[i]);
    }
    
    // Traverse the tree to generate hashmap
    // Not needed if the order of prefix isn't important
    traverse(Tree, "");
    
    // generate ordered result from hashmap
    for(int i = 0; i < A.size(); i++) {
        result.push_back(res[A[i]]);
    }
    
    return result;
}
Example #16
0
// Does one scan iteration. Returns a tuple containing the total number of
// iterations done and left to do for the current scan.
static PyObject *py_iter(PyObject *self, PyObject *args)
{
	static int cur_iter;

	if (!cur_iter)
		cg_idle_mem_stat.clear();

	long start_pfn = cur_iter * iter_span;
	long end_pfn = start_pfn + iter_span;
	if (end_pfn >= END_PFN)
		end_pfn = END_PFN;

	int iters_left = (END_PFN - end_pfn + iter_span - 1) / iter_span;
	cur_iter++;

	try {
		open_files();
		count_idle_pages(start_pfn, end_pfn);
		set_idle_pages(start_pfn, end_pfn);
	} catch (error &e) {
		e.set_py_err();
		return NULL;
	}

	PyObject *ret = Py_BuildValue("(ii)",  cur_iter, iters_left);
	if (!ret)
		return PyErr_NoMemory();

	if (iters_left == 0)
		cur_iter = 0;

	return ret;
}
Example #17
0
const vector<ProfilerDataPoint>& ProfilerGetAccumulatedStatistics()
{
	static vector<ProfilerDataPoint> statistics;
	static unordered_map<DataPointKey, size_t> index;
	statistics.clear();
	index.clear();

	for (const auto& dataPoint : profileData)
	{
		auto key = DataPointKey { dataPoint.filename, dataPoint.line };
		auto indexEntryIter = index.find(key);
		if (indexEntryIter == index.end())
		{
			index[key] = statistics.size();
			statistics.push_back(dataPoint);
		}
		else
		{
			auto& accumulatedStatistics = statistics[indexEntryIter->second];
			assert(accumulatedStatistics.filename == dataPoint.filename);
			assert(accumulatedStatistics.line == dataPoint.line);
			assert(accumulatedStatistics.id == dataPoint.id);
			accumulatedStatistics.duration += dataPoint.duration;
			accumulatedStatistics.hitCount += dataPoint.hitCount;
		}
	}

	return statistics;
}
/*Inititalize an LRU cache with size N */
LRUCache::LRUCache(int N)
{
    ::cap = N;
    head = NULL;
    last = NULL;
    m.clear();
}
// discrete-logarithm, finding y for equation k = x^y % mod
int discrete_logarithm(int x, int mod, int k) {
  if (mod == 1) return 0;
  int s = 1, g;
  for (int i = 0; i < 64; ++i) {
    if (s == k) return i;
    s = (1ll * s * x) % mod;
  }
  while ((g = gcd(x, mod)) != 1) {
    if (k % g) return -1;
    mod /= g;
  }
  static unordered_map<int, int> M; M.clear();
  int q = int(sqrt(double(euler(mod)))) + 1; // mod-1 is also okay
  for (int i = 0, b = 1; i < q; ++i) {
    if (M.find(b) == M.end()) M[b] = i;
    b = (1ll * b * x) % mod;
  }
  int p = fpow(x, q, mod);
  for (int i = 0, b = 1; i <= q; ++i) {
    int v = (1ll * k * inverse(b, mod)) % mod;
    if (M.find(v) != M.end()) {
      int y = i * q + M[v];
      if (y >= 64) return y;
    }
    b = (1ll * b * p) % mod;
  }
  return -1;
}
Example #20
0
int main(void){
	for(int g, p; scanf("%d %d", &p, &g) == 2; ){
		char comp[32], word[32];
		m.clear();
		for(int v1, v2; p-- && scanf("%s %d.%d", word, &v1, &v2) == 3; ) m[word] = v1*10 + v2;
		for(int gn = 0, v; gn++ < g; ){
			int correct, sum = 0;
			while(true){
				scanf("%s %s", word, comp);
				sum += m[word];
				if(*comp == '+') continue;
				scanf("%d", &v);
				v *= 10;
				if(*comp == '<'){
					if(*(comp + 1) == '=') correct = sum <= v;
					else correct = sum < v;
				} else if(*comp == '>'){
					if(*(comp + 1) == '=') correct = sum >= v;
					else correct = sum > v;
				} else correct = sum == v;
				printf("Guess #%d was %s.\n", gn, correct ? "correct" : "incorrect");
				sum = 0;
				break;
			}
		}
	}
	return 0;
}
Example #21
0
	~PartFileCollection() 
	{
		for (auto it = files.begin(); it != files.end(); ++it) {
			delete it->second;
		}
		files.clear();
	}
Example #22
0
int main()
{
/*
#ifndef ONLINE_JUDGE
    freopen ("in.txt" , "r" , stdin);
    freopen ("out.txt" , "w" , stdout);
#endif
*/
    int n, m;
    while(cin>>n>>m)
    {
        hasht.clear(), L.clear();
        for(int i=n;i>=1;i--) L.push_front(i), hasht[i]=L.begin();
        for(int i=0;i<m;i++)
        {
            int x, y;string ins;
            cin>>ins>>x>>y;
            if(ins=="A")
                MoveLeft(x, y);
            else MoveRight(x, y);
        }
        for(auto e: L) cout<<e<<" ";
        cout<<endl;
    }

	return 0;
}
Example #23
0
	~PartFile() 
	{
		for (auto it = parts.begin(); it != parts.end(); ++it) {
			delete it->second;
		}
		parts.clear();
	}
Example #24
0
int main(){
	int ts;cin>>ts;
	for(int i=1;i<=ts;i++){
		cout<<"Case #"<<i<<":\n";
		id.clear();
		m.clear();
		// cout<<id.size()<<" "<<m.size()<<endl;
		for(int i=0;i<10;i++){
			string add;cin>>add;
			int n;cin>>n;
			int id=GI(add);
			m[id]+=n;
		}
		int mx=0;
		for(auto i:m){
			mx=max(mx,i.Y);
		}
		vector<pair<int,string>> anss;
		for(auto i:m){
			if(i.Y==mx){
				auto rt=GN(i.X);
				anss.push_back({rt.Y,rt.X});
			}
		}
		sort(anss.begin(),anss.end());
		for(auto i:anss){
			cout<<i.Y<<endl;
		}
	}
}
int solution(vector<int> &A){
    int res = 0;
    if (A.size() == 0) {
        return res;
    }
    n = 0;
    dict.clear();
    for (int i = 0; i < A.size(); ++ i) {
        if (dict.find(A[i]) == dict.end())
            dict[A[i]] = n ++;
        if (i == 0) {
            s = dict[A[i]];
        }else if(i == A.size() - 1){
            t = dict[A[i]];
        }
    }

    init();
    for (int i = 0; i < A.size() - 1; ++ i) {
        addedge(dict[A[i]], dict[A[i + 1]], 1);
        addedge(dict[A[i + 1]], dict[A[i]], 1);
    }
    if (s == t) {
        return 1;
    }
    dijk();
    res = dist[t] + 1;
    return res;
}
 LRUCache(int capacity) {
 	size = capacity;
     mem.resize(capacity, 0);
     addr.clear(), time.clear();
     memIdx = 0;
     miss = 0;
 }
Example #27
0
float lof_storage::collect_lrds_from_neighbors(
    const vector<pair<string, float> >& neighbors,
    unordered_map<string, float>& neighbor_lrd) const {
  if (neighbors.empty()) {
    return numeric_limits<float>::infinity();
  }

  // collect lrd values of the nearest neighbors
  neighbor_lrd.clear();
  for (size_t i = 0; i < neighbors.size(); ++i) {
    neighbor_lrd[neighbors[i].first] = get_lrd(neighbors[i].first);
  }

  // return lrd of the query
  float sum_reachability = 0;
  for (size_t i = 0; i < neighbors.size(); ++i) {
    sum_reachability += max(neighbors[i].second, get_kdist(neighbors[i].first));
  }

  if (sum_reachability == 0) {
    return numeric_limits<float>::infinity();
  }

  return neighbors.size() / sum_reachability;
}
int main() {
    int T;
    scanf("%d",&T);
    while (T --) {
        scanf("%d",&n);
        int f, s, m = 0;
        dict.clear();
        memset(vis, 0, sizeof(vis));
        for (int i = 0; i < n; ++ i) {
            scanf("%d%d",&f,&s);
            if (dict.find(f) == dict.end() || dict[f].find(s) == dict[f].end()) {
                //pnt[m].first = f;
                //pnt[m].second = s;
                pnts[m].p.first = f;
                pnts[m].p.second = s;
                pnts[m].idx = i + 1;
                ++ m;
                dict[f].insert(s);
            }
        }
        n = m;
        ans = 0;
        covexhull();
        if (T) {
            puts("");
        }
    }
    return 0;
}
Example #29
0
int main()
{
    int N;
    make_pattern(1, vector<int>(10));
    while (cin >> N, N > 0) {
        vector<int> m_cnt(10);
        for (int i = 0; i < N; i++) {
            int m;
            cin >> m;
            m_cnt[m]++;
        }

        int res = 0;
        for (int i = 1; i <= 5; i++) {
            int mini = min(m_cnt[i], m_cnt[10 - i]); 
            if (i == 5) mini /= 2;
            res += mini;
            m_cnt[i] -= mini;
            m_cnt[10 - i] -= mini;
        }
        mem.clear();
        res += solve(m_cnt);
        cout << res << endl;
    }        
    return 0;
}
Example #30
0
void TradeList2TradeMap(list<TradeField*> &tradeList, unordered_map<string, TradeField*> &tradeMap)
{
	// 只在这个函数中new和delete应当没有问题
	for (unordered_map<string, TradeField*>::iterator it = tradeMap.begin(); it != tradeMap.end(); ++it)
	{
		TradeField* pNewField = it->second;
		delete[] pNewField;
	}
	tradeMap.clear();

	// 将多个合约拼接成
	for (list<TradeField*>::iterator it = tradeList.begin(); it != tradeList.end(); ++it)
	{
		TradeField* pField = *it;
		unordered_map<string, TradeField*>::iterator it2 = tradeMap.find(pField->ID);
		if (it2 == tradeMap.end())
		{
			TradeField* pNewField = new TradeField;
			memcpy(pNewField, pField, sizeof(TradeField));
			tradeMap[pField->ID] = pNewField;
		}
		else
		{
			TradeField* pNewField = it2->second;
			pNewField->Price = pField->Price;
			pNewField->Qty += pField->Qty;
		}
	}
}