DNA Sorting
http://poj.org/problem?id=1007
this is ok
#include <stdio.h>
#include <string.h>
struct
{
char s[51];
int sort;
} item[100];
int main(int argc, int argv)
{
int n, m;
scanf("%d %d", &n, &m);
char s[51] = {0};
int sort = 0;
int k = m;
for (k = 0; k < m; k++)
{
scanf("%s", s);
// get the sorted value
sort = 0;
int i = 0;
int na = 0, nc = 0, ng = 0;
for (i = 0; i < n; i++)
{
switch (s[i])
{
case 'A':
na++;
break;
case 'C':
nc++;
break;
case 'G':
ng++;
break;
case 'T':
default:
break;
}
}
for (i = 0; i < n; i++)
{
switch (s[i])
{
case 'A':
na--;
break;
case 'C':
sort = sort + na;
nc--;
break;
case 'G':
sort = sort + na + nc;
ng--;
break;
case 'T':
sort = sort + na + nc + ng;
break;
default:
break;
}
}
strncpy(item[k].s, s, n + 1);
item[k].sort = sort;
}
//sort
int j = 0;
int flag = 0;
for (k = 0; k < m; k++)
{
flag = 0;
for (j = 0; j < m - k - 1; j++)
{
if (item[j].sort > item[j + 1].sort)
{
int tmp = item[j].sort;
item[j].sort = item[j + 1].sort;
item[j + 1].sort = tmp;
strncpy(s, item[j].s, n + 1);
strncpy(item[j].s, item[j+1].s, n + 1);
strncpy(item[j + 1].s, s, n + 1);
flag = 1;
}
}
if (flag == 0)
break;
}
//output
for (k = 0; k < m; k++)
{
printf("%s\n", item[k].s);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
int ln, nu;
scanf("%d %d", &nu, &ln);
char *data = (char *)malloc((nu + 1) * ln + 1);
char *next = data;
int *index = (int *)malloc(sizeof(int) * ln);
int *psort = index;
int *ps = index;
char s[101] = {0};
while (ln--)
{
scanf("%s", s);
s[nu] = '\n';
int i = 0;
int j = 0;
int sort = 0;
for (i = 0; i < nu; i++)
{
for (j = i + 1; j < nu; j++)
if ( *(s + i) > *(s + j))
{
sort++;
}
//printf("%c sort %d\n", *(s+i), sort);
}
//printf("%s %d\n", s, sort);
ps = index;
while (ps < psort)
{
if (sort < *ps)
{
int len = psort - ps;
memmove(ps + 1, ps, len * sizeof(int));
*ps = sort;
int all = psort - index;
memmove(data + (all - len + 1) * (nu + 1),
data + (all - len) * (nu + 1),
len * (nu + 1));
strncpy(data + (all - len) * (nu + 1),
s, nu + 1);
//printf("%s all %d, len %d\n", s, all, len);
break;
}
ps++;
}
if (ps >= psort)
{
*ps = sort;
strncpy(next, s, nu + 1);
}
psort++;
next = next + nu + 1;
}
data[(nu + 1) * ln] = '\0';
printf("%s", data);
free(data);
free(index);
return 0;
}