UVa 1368 - DNA Consensus String

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

題目網址

求出與所有字串相差最少的(漢明距離)。

Solution

直接用每一字串相同位置,出現次數最多的字母去拼成一個字串即為答案。

Code

UVa 1368
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<cstdio>
#include<cstring>
#define N 50
using namespace std;

int main()
{
int ret[20] = {};
ret[0] = 0;//A
ret[2] = 1;//C
ret[6] = 2;//G
ret[19] = 3;//T

char DNA[4] = { 'A', 'C', 'G', 'T' };
char str[N][1001], ans[1001];
int Case;

scanf("%d", &Case);
while (Case--)
{
int n, m, i, j, diff = 0;
scanf("%d%d\r", &n, &m);
for (i = 0; i < n; i++)
gets(str[i]);

for (i = 0; i < m; i++)
{
int count[4] = {};//A,C,G,T
for (j = 0; j < n; j++)
count[ret[str[j][i] - 'A']]++;

int max = 0;
//找出現最多次的
for (int k = 1; k < 4; k++)
if (count[max] < count[k])
{
max = k;
}

ans[i] = DNA[max];
diff += (n - count[max]);//其餘不一樣的字母
}

ans[i] = NULL;
puts(ans);
printf("%d\n", diff);
}

return 0;
}