这么简单的题都出错了。因为忘了把检查过的结果给清除了,所以可能导致重复计算。
比如AT,TA,AT这样的输入,应该只能组成一组,如果组完后没有丢弃AT,TA,就会导致检查完AT后继续检查TA,然后将已经使用过的TA去和AT做匹配!
先贴下错误代码:
#include <iostream>
using namespace std;
bool match_c(char a, char b) {
if( a == 'A' && b == 'T' )
return true;
else if ( a == 'T' && b == 'A')
return true;
else if ( a == 'C' && b == 'G')
return true;
else if ( a == 'G' && b == 'C')
return true;
else
return false;
}
bool match(string a, string b){
int len = a.size();
int i;
if( len != b.size() )
return false;
else{
for( i = 0; i < len; i++) {
if( !match_c(a[i], b[i] ))
return false;
}
return true;
}
}
int main() {
int T, n;
int i, j, k;
int count;
string d[100];
cin >> T;
for( i = 0; i < T; i++ ) {
cin >> n;
for ( j = 0; j < n; j++) {
cin >> d[j];
}
count = 0;
for ( j = 0; j < n; j++ ) {
for( k = j+1; k < n; k++ ) {
if( match(d[j], d[k]) )
count++;
}
}
cout << count << endl;
}
}
然后正确代码:
#include <iostream>
using namespace std;
bool match_c(char a, char b) {
if( a == 'A' && b == 'T' )
return true;
else if ( a == 'T' && b == 'A')
return true;
else if ( a == 'C' && b == 'G')
return true;
else if ( a == 'G' && b == 'C')
return true;
else
return false;
}
bool match(string a, string b){
int len = a.size();
int i;
if( len != b.size() )
return false;
else{
for( i = 0; i < len; i++) {
if( !match_c(a[i], b[i] ))
return false;
}
return true;
}
}
int main() {
int T, n;
int i, j, k;
int count;
string d[101];
cin >> T;
for( i = 0; i < T; i++ ) {
cin >> n;
for ( j = 0; j < n; j++) {
cin >> d[j];
}
count = 0;
for ( j = 0; j < n; j++ ) {
if (d[j] != "") {
for( k = j+1; k < n; k++ ) {
if( d[k] != "" && match(d[j], d[k]) ) {
d[j] = "";
d[k] = "";
count++;
}
}
}
}
cout << count << endl;
}
return 0;
}
转载于:https://blog.51cto.com/xuewei/1348511