コード例 #1
0
ファイル: a.cpp プロジェクト: meysamaghighi/Kattis
bool check(trie<char> &t, string s, int steps, int digits){
    // cerr << s << endl;
    if (steps < digits) return false;
    if (steps == 0) return (bool)t.countMatches(s.begin(), s.end());
    if (t.countMatches(s.begin(), s.end())) return true;
    if (digits){
        for (int i=0;i<s.size();i++){
            if (isdigit(s[i])){
                for (s[i] = 'a'; s[i] <= 'z'; s[i]++){                                        
                    if (check(t, s, steps-1, digits-1)) return true;                    
                }
                for (s[i] = 'A'; s[i] <= 'Z'; s[i]++){
                    if (check(t, s, steps-1, digits-1)) return true;
                }
            }
        }
    }
    else {
        for (int i=0; i<s.size()-1; i++){
            swap(s[i], s[i+1]);
            if (check(t, s, steps-1, digits)) return true;
            swap(s[i], s[i+1]);
        }
    }
    return false;
}
コード例 #2
0
 WordFilter(vector<string> words) {
   for (int i = 0; i < words.size(); i++) {
     t_prefix.insert(words[i], i);
     reverse(words[i].begin(), words[i].end());
     t_suffix.insert(words[i], i);
   }
 }
コード例 #3
0
void makeTrie(void) {
    map<int, hostConf>::iterator j;
    string::iterator stringit;
    char* temp = new char[16];
    string prestring;
    char* size = new char[2];
    struct cidrprefix tempFix;
    for(j = routerEnd.begin(); j != routerEnd.end(); j++) {
        prestring = (j->second).overlayPrefix;
        for(stringit = prestring.begin(); stringit != prestring.end(); stringit++) {
			if(*stringit == '/') {
				strcpy(temp, prestring.substr(0, distance(prestring.begin(),stringit)).c_str());
				cout << "Temp: " << temp << endl;
				inet_pton(AF_INET, temp, (void *)&tempFix.prefix);
				stringit++;
				size[0] = *stringit;
				stringit++;
				size[1] = *stringit;
				break;
			}
        }
        tempFix.size = (char)atoi(size);
        #ifdef DEBUG
			cout << "Prefix: " << tempFix.prefix << "/" << (int)tempFix.size << " for router: " << routerIPs[j->first] << endl;
		#endif
        hosts.insert(tempFix, routerIPs[j->first]);
        #ifdef DEBUG
			cout << "Testing trie." << endl;
			int testaddr;
			inet_pton(AF_INET, "1.2.3.1", (void *)&testaddr);
			cout << testaddr << hosts.search(testaddr) << endl;
		#endif
    }
    
}
コード例 #4
0
ファイル: FindStrings.cpp プロジェクト: znameroski/IS
/**
 * Conducts behavior described in "Find Strings" problem
 */
int main (){

	int n,q;
	cin >> n; //get n


	if((n < 1) || (n > 50)){
		cout << "INVALID";  //1<=n<=50
		return 0;
	}
	string mystr;
	for(int i = 0; i < n; i++){

		cin >> mystr; //get string

		if((mystr.length() > 2000) || (mystr.length() < 1)){
			cout << "INVALID";  //1<=mi<=2000
			return 0;
		}
		else{
			trie.insert(mystr);
		}

	}


	trie.print();
	trie.enum_substrings(substrings);
	sort(substrings.begin(), substrings.end());
	it = unique(substrings.begin(), substrings.end());
	substrings.resize(it - substrings.begin());
	print_elements(substrings);

	cin >> q; //get q


	if((q < 1) || (q > 500)){
		cout << "INVALID";  //1<=q<=500
		return 0;
	}
	else{
		int myk;
		for(int i = 0; i < q; i++){

			cin >> myk; //get substring index

			if(myk > substrings.size() || ((myk > 1000000000) || (myk < 1))){
				kstrings.push_back("INVALID"); //1<=k<=1000000000
			}
			else{
				kstrings.push_back(substrings[myk - 1]);
			}
		}
		print_elements(kstrings);
	}

	return 0;
}
コード例 #5
0
ファイル: dADS2-09-5b.cpp プロジェクト: Mortal/dADS2-opg5
	void operator()(trie<suffix_payload> & t) {
		t.payload.is_orig = false;
		t.payload.is_rev = false;
		if (t.ch == END1) {
			t.payload.is_orig = true;
			return;
		}
		if (t.ch == END2) {
			t.payload.is_rev = true;
			return;
		}
		for (auto i = t.children.begin(); i != t.children.end(); ++i) {
			if (i->second.payload.is_orig) {
				t.payload.is_orig = true;
			}
			if (i->second.payload.is_rev) {
				t.payload.is_rev = true;
			}
		}
		if (t.payload.is_orig && t.payload.is_rev) {
			if (t.payload.depth > 1) {
				cout << t.path() << endl;
			}
		}
	}
コード例 #6
0
ファイル: ambiguos.cpp プロジェクト: jccarvalhosa/maratona
void generate(string s, int val)
{
	queue<string> q;
	int i, h, pai, filho;
	if(m.count(s) == 0)
	{
		m[s] = m.size() - 1;
		q.push(s);
	}
	pai = m[s];
	tam[pai] = val;
	while(!q.empty())
	{
		s = q.front();
		pai = m[s];
		q.pop();
		if(tam[pai] > resp) continue;
        query.clear();
        t.match(s, 0); 
        for(i=0;i<query.size();i++)
		{
			if(!sufix(s, query[i])) continue;
            if(m.count(sufstr) == 0)
            {
                m[sufstr] = m.size() - 1;
                filho = m.size() - 1;
                q.push(sufstr);
            }
            else filho = m[sufstr];
            tam[filho] = tam[pai] + sufdis;
            grafo[pai].push_back(filho);
            peso[pai].push_back(sufdis);
		}
	}
}
コード例 #7
0
 AutocompleteSystem(vector<string> sentences, vector<int> times) {
   for (int i = 0; i < sentences.size(); i++) {
     for (int j = 0; j < times[i]; j++)
       tr.insert(sentences[i]);
   }
   node = &tr;
 }
コード例 #8
0
int main()
{
    while (true)
    {
        scanf("%d%d",&n,&m);
        if (n == 0 && m == 0)   break;
        ac.init();
        for (int i = 0; i < n; i++)
        {
            scanf("%s",buf);
            ac.insert(buf,i);
        }
        for (int i = 0; i < m; i++)
        {
            scanf("%s",buf);
            ac.insert(buf,-1);
        }
        ac.build();
        tot = 0;
        pos[tot++] = 0;
        for (int i = 0; i < ac.L; i++)
            if (ac.endv[i] == false && ac.endr[i] != 0)
                pos[tot++] = i;
        for (int i = 0; i < tot; i++)
            Gao(i);
        memset(dp,-1,sizeof(dp));
        dp[0][0] = 0;
        for (int i = 0; i < (1<<n); i++)
            for (int j = 0; j < tot; j++)
                if (dp[i][j] != -1)
                    for (int k = 0; k < tot; k++)
                        if (d[j][k] != -1)
                        {
                            int newsta = i|ac.endr[pos[k]];
                            if (dp[newsta][k] == -1 || dp[newsta][k] > dp[i][j]+d[j][k])
                                dp[newsta][k] = dp[i][j]+d[j][k];
                        }
        int res = -1;
        for (int i = 0; i < tot; i++)
            if (dp[(1<<n)-1][i] != -1)
                if (res == -1 || res > dp[(1<<n)-1][i])
                    res = dp[(1<<n)-1][i];
        printf("%d\n",res);
    }
    return 0;
}
コード例 #9
0
ファイル: ambiguos.cpp プロジェクト: jccarvalhosa/maratona
int main()
{
	int N, i, j, k;
	vector<string> init;
	vector<int> start;
    string str;
	char s[100];
	while(scanf("%d", &N) != EOF && N)
	{
		v.clear();
		init.clear();
		start.clear();
        t.children.clear();
		for(i=0;i<m.size();i++)
		{
			grafo[i].clear();
			peso[i].clear();
			tam[i] = INF;
		}
		m.clear();
		m[""] = 0;
		for(i=0;i<N;i++)
		{
			scanf("%s", s);
            t.insert(s, 0);
            v.push_back(s);
		}
		for(i=0;i<v.size();i++)
        {
            query.clear();
            t.match(v[i], 0);
            for(j=0;j<query.size();j++) if(query[j] != v[i])
            {
                if(!sufix(v[i], query[j])) continue;
                init.push_back(sufstr);
                start.push_back(max(v[i].size(), query[j].size()));
            }
		}
		resp = INF;
		for(i=0;i<init.size();i++) if(start[i] < resp) resp = min(resp, shortest_path(init[i], start[i]));
		if(resp == INF) printf("-1\n");
		else printf("%d\n", resp);
	}
	return 0;
}
コード例 #10
0
ファイル: trie.hpp プロジェクト: jamella/learning-fuzzing
/// \brief Returns size and total sum of symbols
template <typename T> std::pair<size_t, size_t> total_size(trie<T> const & t) {
	size_t count = 0;
	size_t total_count = 0;
	t.for_each([&count, &total_count](std::vector<T> const &  w) {
		++count;
		total_count += w.size();
	});
	return {count, total_count};
}
コード例 #11
0
  vector<string> input(char c) {
    vector<string> r;

    if (c == '#') {
      tr.insert(s);
      s.clear();
      node = &tr;
      return r;
    }

    s.push_back(c);

    if (node != nullptr) {
      node = node->get_next(c);
      if (node != nullptr)
        return node->get_top3();
    }

    return r;
  }
コード例 #12
0
  int f(string prefix, string suffix) {
    auto p = t_prefix.find(prefix);
    reverse(suffix.begin(), suffix.end());
    auto q = t_suffix.find(suffix);
    if (p == nullptr || q == nullptr) return -1;

    auto m = p->get();
    auto n = q->get();
    int i = m.size()-1;
    int j = n.size()-1;
    while (i>= 0 && j >= 0 && m[i] != n[j]) {
      if (m[i] > n[j]) {
        i--;
      }
      else {
        j--;
      }
    }

    if (i >= 0 && j >= 0 && m[i] == n[j])
      return m[i];
    return -1;
  }
コード例 #13
0
ファイル: jump.cpp プロジェクト: elvircrn/ccppcodes
int main()
{
    freopen ("input.txt", "r", stdin);
    scanf ("%d", &n); getchar();

    bool new_sentence = false;

    while(n--)
    {
        char c = 0;
        do
        {
            c = getchar();

            if (c == EOF)
                break;
            else if (!isalnum(c) && new_sentence)
                continue;
            else if (c == '?')
            {
                new_sentence = true;
                //flush

                printf ("SHIT:\n");
                for (int i = 0; i < shit.size(); i++)
                    putchar (shit[i]); putchar('\n');

                sentence_count += _trie.flush();

                shit.clear();
            }
            else if (c == '.' || c == '!')
            {
                new_sentence = true;
            }
            else if (c != '\n')
            {
                shit.push_back(c);
            }
        } while (c != '\n');


        if (c == EOF)
            break;
    }

    printf ("sentence_count: %d\n", sentence_count);

    return 0;
}
コード例 #14
0
	void find(string &str, int pos, int bitm, ll lvl = 0){
		bitmask |= bitm;
		if(bitmask == finalbit){
			res = max(res, lvl);
		}
		if(pos == str.length() or lvl > 60){
			return;
		}


		if(str[pos] == 'a'){
			if(a == NULL){
				a = new trie;
			}

			a->find(str, pos + 1, bitm, lvl + 1);
		} else {
			if(b == NULL){
				b = new trie;
			}

			b->find(str, pos + 1, bitm, lvl + 1);
		}
	}
コード例 #15
0
int main() {
	ios::sync_with_stdio(false);

	int n;
	cin >> n;
	finalbit = (1 << n) - 1;

	for(int i = 0; i < n; i++){
		string str;
		cin >> str;

		for(int j = 0; j < str.length(); j++){
			root.find(str, j, 1 << i);
		}
	}

	cout << res;
	return 0;
}
コード例 #16
0
ファイル: trie.hpp プロジェクト: jamella/learning-fuzzing
/// \brief Flattens a trie \p t
/// \returns an array of words (without the prefixes)
template <typename T> std::vector<std::vector<T>> flatten(trie<T> const & t) {
	std::vector<std::vector<T>> ret;
	t.for_each([&ret](std::vector<T> const & w) { ret.push_back(w); });
	return ret;
}
コード例 #17
0
ファイル: D (15).cpp プロジェクト: elvircrn/ccppcodes
int main()
{
	cout<<"KOAKSODKASdokasdo\n";
	
    _trie = trie();

    for (int i = 0; i < 500100; i++)
        finished [i] = turns_into [i] = -1;

    scanf ("%d", &n); getchar();
    for (int i = 0; i < n; i++)
        _trie.parse_input();

    for (int i = 0; i < words.size(); i++)
        printf ("%d ", words [i]); printf ("\n");


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

    for (int i = 0; i < m; i++)
    {
        int X = _trie.parse_input();
        int Y = _trie.parse_input();

        printf ("%d %d\n", X, Y);
        turns_into[X] = Y;
        cool [X] = true;

        QMAX = max (X, Y);
    }

    QMAX = max (QMAX, word_index);

    int R = 0, L = 0;

    for (int i = 0; i < words.size(); i)
    {
        if (turns_into [words [i]] == -1)
        {
            R += R_count [words [i]];
            L += lengths [words [i]];
        }
        else if (finished [words [i]])
        {
            R += R_count [words [i]];
            L += lengths [words [i]];
        }
        else
        {
            stacks.clear();
            int current_index = words [i];
            int q = i - 1;

            while (finished [current_index] != -1)
            {
                stacks.push_back(current_index);
                finished[current_index] = 1;
                current_index = turns_into [current_index];
            }
            stacks.push_back(current_index);

            int MAXR = R_count[current_index];
            int MAXL = lengths[current_index];

            for (int j = stacks.size() - 2; j > -1; j--)
            {
                if (R_count [stacks [j]] == R_count [stacks [j - 1]])
                {
                    R_count[stacks [j]] = R_count[stacks [j + 1]];
                }
            }
        }
    }

    return 0;
}
コード例 #18
0
ファイル: dADS2-09-5b.cpp プロジェクト: Mortal/dADS2-opg5
	void calc() {
		t.pre_order_traversal(depth_calc());
		t.post_order_traversal(lsr_calc());
	}
コード例 #19
0
ファイル: dADS2-09-5b.cpp プロジェクト: Mortal/dADS2-opg5
	void set_string(string s) {
		t.insert_suffixes(s + END1);
		t.insert_suffixes(string(s.rbegin(), s.rend()) + END2);
	}
コード例 #20
0
int main(int argc, char** argv) {
    #ifdef SANDWICH
        printf("I'm a sandwich!\n");
    #endif
    int o;
    string configPath;
    char isRouter = IP_NOT_FOUND;
    while((o = getopt(argc, argv, "rh")) != -1) {
		switch(o) {
			case 'r':
				//enter router mode
				isRouter = TRUE;
				break;
			case 'h':
				//enter host mode
				isRouter = FALSE;
				break;
			case '?':
			    fprintf(stderr, "Unknown option -%c.\n", optopt);
			    cout << "Specify host with -h or router with -r" << endl;
			    exit(0);
				break;
		}
	}
	configPath = (string)argv[optind];
	if(configPath.empty()) {
		printf("Please, you must provide a filename.\n");
		printf("Usage: overlay [-r -h] config.conf\n");
		exit(1);
	}
	readConfig(configPath);
    makeTrie();
    struct ifaddrs *demAddrs;
    if(getifaddrs(&demAddrs)) {
		fprintf(stderr, "Couldn't get real IP address. Aborting.\n");
		exit(1);
	}
	struct in_addr *myAddr;
	char* addrBuf = new char[INET_ADDRSTRLEN];
	struct sockaddr *mysockaddr = (demAddrs->ifa_addr);
	while((strcmp(demAddrs->ifa_name, "eth0") && strcmp(demAddrs->ifa_name, "eth1") && strcmp(demAddrs->ifa_name, "eth2") && strcmp(demAddrs->ifa_name, "eth3") && strcmp(demAddrs->ifa_name, "wlan0"))||(mysockaddr->sa_family!=AF_INET)) {
		#ifdef DEBUG
			cout << "Interface: " << demAddrs->ifa_name << ". NOPE!" << endl;
		#endif
	    demAddrs = demAddrs->ifa_next;
	    if(demAddrs==NULL) {
		    fprintf(stderr, "Couldn't find the specified interface. Aborting. Sorry! Make sure your computer is set up properly.\n");
		    exit(1);
	    }
	    mysockaddr = (demAddrs->ifa_addr);
	}
	#ifdef DEBUG
		cout << "Interface: " << demAddrs->ifa_name << endl;
	#endif
	myAddr = &(((struct sockaddr_in*)mysockaddr)->sin_addr);
	inet_ntop(AF_INET, (void *)myAddr, addrBuf, INET_ADDRSTRLEN);
	#ifdef DEBUG
		printf("My real IP address is: %s\n", addrBuf);
	#endif
	map<int, string>::iterator routeit;;
	for(routeit = routerIPs.begin(); routeit != routerIPs.end(); routeit++) {
		#ifdef DEBUG
			cout << "Testing: " << (*routeit).second << endl;
		#endif
		if(!(*routeit).second.compare((string)addrBuf)) {
			isRouter = TRUE;
			hostID = (*routeit).first;
			break;
		}
	}
	if(isRouter == IP_NOT_FOUND) {
		map<int, hostIP>::iterator endit;
		for(endit = endIPs.begin(); endit != endIPs.end(); endit++) {
			#ifdef DEBUG
				cout << "Testing: " << (*endit).second.real << endl;
			#endif
			if(!(*endit).second.real.compare((string)addrBuf)) {
				isRouter = FALSE;
				hostID = (*endit).first;
				break;
			}
		}
	}
	if(isRouter == IP_NOT_FOUND) {
		fprintf(stderr, "I couldn't find your IP address in my memory banks. Please check to make sure your configuration file is correct.");
		exit(1);
	}
	if(isRouter) router();
	else {
		uint32_t myIP = 0;
		inet_pton(AF_INET, endIPs[hostID].overlay.c_str(), (void *)&myIP);
		string myRouter = hosts.search(myIP);
		#ifdef DEBUG
			cout << "My router is: " << myRouter << endl;
		#endif
		unsigned long myRouterInt;
		inet_pton(AF_INET, myRouter.c_str(), (void *)&myRouterInt);
		host(myRouterInt);
	}
	return 0;
}
コード例 #21
0
void router(void) {
	#ifdef DEBUG
		cout << "I am router #" << hostID << "!" << endl;
	#endif
    //bind socket 
    int sockfd = create_cs3516_socket();
    //initialize for select() call
    fd_set readfds;
	FD_ZERO(&readfds);
	FD_SET(sockfd, &readfds);
	//We want a truly nonblocking call so...
	struct timeval timeoutval;
	timeoutval.tv_sec = 10;
	timeoutval.tv_usec = 0;
    map<string, deque<struct message *> > outputbuffers;
    map<int, hostIP>::iterator it;
    struct cidrprefix tempFix;
    for(it = endIPs.begin(); it != endIPs.end(); it++) {
		inet_pton(AF_INET, (*it).second.overlay.c_str(), (void *)&tempFix.prefix);
		tempFix.size = 32;
		hosts.insert(tempFix, (*it).second.real);
		outputbuffers[(*it).second.real] = *(new deque<struct message *>);	//Try to access the output buffer for this IP, but since it won't exist, create one.
		#ifdef DEBUG
			cout << "I just inserted " << hosts.search(tempFix.prefix) << endl;
		#endif
	}
		
    while(TRUE){
        //check if we have anything to read
        FD_ZERO(&readfds);
		FD_SET(sockfd, &readfds);
        select(sockfd+1, &readfds, NULL, NULL, &timeoutval);
        //while we have a packet to receive, handle it
        if(FD_ISSET(sockfd, &readfds)){
			#ifdef DEBUG
				cout << "Received a packet!" << endl;
			#endif
            struct message *receivemessage = new struct message();
            receivemessage->buffer = (char*)malloc(MAX_PACKET_SIZE);
            cs3516_recv(sockfd, receivemessage->buffer, MAX_PACKET_SIZE);
            time(&(receivemessage->recvtime));
            iphdr *ip = (iphdr*)(receivemessage->buffer);
	        
	        //get the real ip address of the destination
	        string interface = hosts.search((uint32_t)(ip->daddr)); 
	        cout << "Going to router: " << interface << endl;
	        deque<struct message *> outputqueue;
	        //Get some info from the packet for logging purposes
	        char srcstr[INET_ADDRSTRLEN], dststr[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, &(ip->saddr), srcstr, INET_ADDRSTRLEN);
	        inet_ntop(AF_INET, &(ip->daddr), dststr, INET_ADDRSTRLEN);
	        cout << "This fella is going to " << dststr << endl;
	        short id = ntohs(ip->id);
	        //get the output queue
	        cout << "Interface: " << interface << endl;
	        if(outputbuffers.find(interface)!=outputbuffers.end()){
	            outputqueue = outputbuffers.find(interface)->second;
	        } else {
	            //we don't know who this is! Log it and drop that packet like it's hot
	            writetolog(srcstr, dststr, id, "NO_ROUTE_TO_HOST", "");
	            continue;
	        }
	        //decrement the ttl value
            (ip->ttl)--;
            if((ip->ttl)>0){
                if(outputqueue.size()<=configuration.queueLength){
                    outputbuffers[interface].push_back(receivemessage);
                    writetolog(srcstr, dststr, id, "SENT_OK", interface);
                } else {
                    //drop the packet and log
                    writetolog(srcstr, dststr, id, "MAX_SENDQ_EXCEEDED", "");
                }
            } else {
                //drop the packet and log
                writetolog(srcstr, dststr, id, "TTL_EXPIRED", "");
            }
        }
        //look at queues to see if any send delays have elapsed
        //TODO per-queue send delay as specified by the assignment
	    for(map<string, deque<struct message *> >::iterator i = outputbuffers.begin(); i != outputbuffers.end(); i++) {
	    	string interface = (*i).first;
	    	double delay = 0;
	    	bool isRouter = false;
	    	int hostToSend = lookupHost(interface, &isRouter);
	    	if(isRouter)
				delay = routerRouter[hostToSend].sendDelay;
			else
				delay = routerEnd[hostToSend].sendDelay;
	    	deque<struct message *> buffer = (*i).second;
		    if(buffer.size()>0){
		        struct message* currentmsg = buffer.front();
		        time_t currenttime;
		        time(&currenttime);
		        double waited = difftime(currenttime, currentmsg->recvtime);
		        if(waited>(delay/1000)){
		            unsigned int interfacebytes;
		            //convert address to bytes
		            inet_pton(AF_INET, (char*)interface.c_str(), (void *)&interfacebytes);
		            #ifdef DEBUG
						cout << "Down to the nitty-gritty: sending the packet." << endl;
					#endif
		            int status = cs3516_send(sockfd, currentmsg->buffer, MAX_PACKET_SIZE, interfacebytes);
                    //if(status) sent = TRUE;
                    if(!status) fprintf(stderr, "There was an error sending the file. No bytes were sent.");
                    //free(currentmsg->buffer);
                    delete currentmsg;
                    outputbuffers[interface].pop_front();
                }
		    }
	    }
    }
}
コード例 #22
0
ファイル: test_trie.cpp プロジェクト: bilbil/enhance
    cout <<"test callback 1" << endl;
    return true;
}
bool test_callback2(){
    cout <<"test callback 2" << endl;
    return true;
}
bool test_callback3(){
    cout <<"test callback 3" << endl;
    return false;
}

TEST_CASE( "trie", "[trie]" ) {
      
    bool bRet;
    trie<int, std::function<bool(void)> > _trie;

    SECTION( "insert and retrieve items" ) {
	queue< int > keys1;
	keys1.push(3);
	keys1.push(1);
    
	queue< int > keys2;
	keys2.push(3);
	keys2.push(5);
	keys2.push(0);
    
	queue< int > keys3;
	keys3.push(7);

	std::function<bool(void)> f1 = test_callback1;
コード例 #23
0
 bool next_match(const char*& aString)
 {
   aString = ansString;
   return t->next_match(queryString,ansString);
 }