写这段代码时遇到了几个困难:
1,对STL不熟悉,或者可以说一知半解吧。
2,明确算法后,居然不会用一些数据结构表示出来。
3,对于无限循环,可以用两个结构迭代下去。
1 #include<iostream> 2 #include<string>
3 #include<set>
4 #include<cstdlib>
5 using namespace std;
6 bool testFront(string a, string b){
7 for(int i = 0 ; i < b.length(); i++)
8 if(b[i] != a[i])
9 return false;
10 return true;
11 }
12 string getLast(string a,string b){
13 string t(a.length() - b.length(),0);
14 for(int i = 0 ; i <t.length() ; i++)
15 t[i] = a[i + b.length()];
16 return t;
17 }
18
19 int main(){
20 int count,cnt;
21 set<string> container;
22 string temp;
23 cout << "输入码字集的大小" << endl;
24 cin >> count;
25 cout <<"输入码字的个数" << endl;
26 cin >> cnt;
27 cout << "逐个输入码字" << endl;
28 for(int i = 1; i <= cnt; i++){
29 cin >> temp;
30 if(container.find(temp) != container.end()){
31 cout << "奇异码!" << endl;
32 exit(1);
33 }
34 else container.insert(temp);
35 }
36 cout << "非奇异码!" << endl;
37 //craft
38 double res = 0;
39 set<string> f;
40 set<string> ::iterator i,j;
41 for( i = container.begin();
42 i != container.end();i++){
43 double temp = 1;
44 for(int j = 1; j <= (*i).length(); j++)
45 temp *= count;
46 res += (1/temp);
47 }
48 if(res > 1){
49 cout << "不满足craft不等式" << endl;
50 exit(1);
51 }
52 else cout << "满足craft不等式" << endl;
53 int flag = 1;
54 for( i = container.begin();
55 i != container.end();i++){
56 j= i;
57 j++;
58 for( ;j != container.end();j++){
59 string a,b;
60 if((*i).length() > (*j).length()){
61 a = *i;
62 b = *j;
63 }
64 else {
65 a = *j;
66 b = *i;
67 }
68 if(testFront(a,b)){
69 cout << b <<"是" << a << "的前缀" << endl;
70 flag = 0;
71 string t = getLast(a,b);
72 if(!t.empty()){
73 f.insert(t);
74 if(container.find(t) != container.end()){
75 cout << " 不是唯一可译码!" ;
76 cout << t << "在C内!"<<endl;
77 exit(1);
78 }
79 }
80 }
81 }
82 }
83 if(!flag)
84 cout << "不是即时码!" <<endl;
85 else {
86 cout << "是即时码!" << endl;
87 exit(1);
88 }
89 set<string> ft1(f),ft2;
90 int tc = 1;
91 while(1){
92 cout << tc << ':';
93 tc ++;
94 int flag = 0;
95 for(i = ft1.begin(); i != ft1.end();i++){
96 for(j = container.begin();
97 j != container.end();j++){
98 string a,b;
99 if((*i).length() > (*j).length()){
100 a = *i;
101 b = *j;
102 }
103 else {
104 a = *j;
105 b = *i;
106 }
107 if(testFront(a,b)){
108 string t = getLast(a,b);
109 if(container.find(t) != container.end()){
110 cout << "不是唯一可译码!" <<t << "在C内" << endl;
111 exit(1);
112 }
113 if(f.find(t) == f.end())
114 ft2.insert(t);
115 }
116 }
117 }
118 if(ft2.empty()){
119 cout << "是唯一可译码" << endl;
120 exit(1);
121 }
122 for(i = ft1.begin();i != ft1.end();i++){
123 f.insert(*i);
124 cout << *i << ' ';
125 }
126 ft1.clear();
127 ft1 = ft2;
128 ft2.clear();
129 }
130 }
131