All pastes #408965 Raw Edit

Miscellany

public cpp v1 · immutable
#408965 ·published 2007-03-25 09:17 UTC
rendered paste body
/* Author :Ravi Shankar.T */#include <iostream>#include <fstream>#include <cstring>#include <string>#include <list>#include <cctype>#include <cassert>using namespace std;#define	REP(i,n)	for(int i=0;i<(n);++i)#define FOR(i,a,b)	for(int i=(a);i<=(b);++i)#define FORD(i,a,b)	for(int i=(a);i>=(b);--i)#define FIT(i,c,t)	for(t::iterator i=(c).begin();i!=(c).end();++i)#define SET(arr,val)	memset((arr),(val),sizeof(arr))typedef list<string> L_S;const int CHSZ=27;class Trie {	public:		Trie () 													// next[0] used to specify if this Trie is the End of a word		{			REP (i, CHSZ) next[i] = NULL;		}		Trie *insert (int ch) 		{			assert(isalpha(ch) || ch=='\0');			if (ch!='\0')				ch = ch-'a'+1;										// Convert it into a index for next			if (next[ch] == NULL)				next[ch] = new Trie;			return next[ch];		}		Trie *insert (const char *inp) 		{			Trie *trie = this;			for (int i=0; inp[i]; ++i) 				trie = trie->insert(inp[i]);			trie->insert('\0');			return trie;		}		void print(string prefix="")		{			for (int i=0; i<CHSZ; ++i) {				if (this->next[i]) {					if (i!=0)						(this->next[i])->print(prefix+((char)('a'-1+i)));					else cout<<prefix<<endl;				}			}		}		bool is_composite_word (int M, const char *inp)		{			if (M<1) M=1;			Trie *trie=this;			while(*inp) {				trie = trie->next[*(inp++)-'a'+1];				if (trie==NULL) return false;				if (trie->next[0]) {					if (this->is_composite_word(M-1, inp)) return true;				}			}			if (*inp=='\0' && M==1 && trie->next[0])				return true;			return false;		}	private:		char ch; 		Trie *next[CHSZ];};int main (int argc, char *argv[]){	Trie trie;	L_S inp_list;	string tmp;	ifstream fin(argv[1]);	while ( getline(fin, tmp) ) {		if (tmp.size() < 3) continue;		inp_list.push_back(tmp);		trie.insert (tmp.c_str());	}	int M;	sscanf (argv[2], "%d", &M);	int composite_word_count = 0;	FIT (it, inp_list, L_S) {		if (trie.is_composite_word( M, it->c_str()))			++composite_word_count;	}	cout<<composite_word_count<<endl;	return 0;}