http://poj.org/problem?id=1007
DNA Sorting
Time Limit: 1000MS | | Memory Limit: 10000K |
Total Submissions: 66142 | | Accepted: 26179 |
Description
One measure of ``unsortedness'' in a sequence is the number of pairs of entries that are out of order with respect to each other. For instance, in the letter sequence ``DAABEC'', this measure is 5, since D is greater than four letters to its right and E is greater than one letter to its right. This measure is called the number of inversions in the sequence. The sequence ``AACEDGG'' has only one inversion (E and D)---it is nearly sorted---while the sequence ``ZWQM'' has 6 inversions (it is as unsorted as can be---exactly the reverse of sorted).
You are responsible for cataloguing a sequence of DNA strings (sequences containing only the four letters A, C, G, and T). However, you want to catalog them, not in alphabetical order, but rather in order of ``sortedness'', from ``most sorted'' to ``least sorted''. All the strings are of the same length.
Input
The first line contains two integers: a positive integer n (0 < n <= 50) giving the length of the strings; and a positive integer m (0 < m <= 100) giving the number of strings. These are followed by m lines, each containing a string of length n.
Output
Output the list of input strings, arranged from ``most sorted'' to ``least sorted''. Since two strings can be equally sorted, then output them according to the orginal order.
Sample Input
10 6
AACATGAAGG
TTTTGGCCAA
TTTGGCCAAA
GATCAGATTT
CCCGGGGGGA
ATCGATGCAT
Sample Output
CCCGGGGGGA
AACATGAAGG
GATCAGATTT
ATCGATGCAT
TTTTGGCCAA
TTTGGCCAAA
Source
题意:
输入m个长度为n的DNA序列,把他们按照逆序数从小到大稳定排序输出。
PS:“稳定排序”就是当序列中出现A1==A2时,排序前后A1与A2的相对位置不发生改变。
解题思路:
没难度,先求各个字符串的逆序数,再按逆序数对字符串快排,用qsort()函数。
虽然快排不是稳定的排序,但是只要在定义排序规则函数cmp做适当处理,a==b时返回0,即不处理a和b,就不会改变他们之间的相对位置了。这题纠结在怎么把比较完的字符串按照比较后的结果输出。网上看到的n[i]=n[i]*1000+i;输出时用 printf("%s\n",a[n[i]00]);真是大神啊。。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char a[101][101];
int n[101];
int cmp(const void*a,const void*b)
{
return ((*(int*)a-*(int*)b));
}
int main()
{
int r,c,i,j,m;
scanf("%d %d",&r,&c);
for(i=0;i<c;i++)
{
scanf("%s",a[i]);//这边也十分值得借鉴
for(j=0;j<r;j++)
for(m=j+1;m<r;m++)
{
if(a[i][j]>a[i][m])
n[i]++;
}
n[i]=n[i]*1000+i;//妙啊
}
qsort(n,c,sizeof(n[0]),cmp);
for(i=0;i<c;i++)
printf("%s\n",a[n[i]%1000]);
return 0;
}
代码2:个人来说比较喜欢这种。。。http://blog.csdn.net/woshixingaaa/article/details/5589070
#include<iostream>
#include<algorithm>
using namespace std;
struct f
{
int num;
char w[50];
}s[101];
bool cmp(struct f a,struct f b)
{
return a.num<b.num ;
}
int main()
{
int i,len,n,j,k;
cin>>len>>n;
for(i=0;i<n;i++)
{
s[i].num =0;
cin>>s[i].w;
for(j=1;j<len;j++)
{
for(k=0;k<j;k++)
{
if(s[i].w[j]<s[i].w[k])
s[i].num++;
}
}
}
sort(s,s+n,cmp);
for(i=0;i<n;i++)
cout<<s[i].w<<endl;
return 0;
}