http://poj.org/problem?id=1007
DNA Sorting
Time Limit: 1000MSMemory Limit: 10000KTotal Submissions: 66142Accepted: 26179Description
One measure of ``unsortedness''in a sequence is the number of pairs of entries that are out oforder with respect to each other. For instance, in the lettersequence ``DAABEC'', this measure is 5, since D is greater thanfour letters to its right and E is greater than one letter to itsright. This measure is called the number of inversions in thesequence. The sequence ``AACEDGG'' has only one inversion (E andD)---it is nearly sorted---while the sequence ``ZWQM'' has 6inversions (it is as unsorted as can be---exactly the reverse ofsorted).
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, butrather in order of ``sortedness'', from ``most sorted'' to ``leastsorted''. All the strings are of the same length.
Input
The first line contains twointegers: a positive integer n (0 < n<= 50) giving the length of the strings; and apositive integer m (0 < m <= 100)giving the number of strings. These are followed by m lines, eachcontaining a string of length n.
Output
Output the list of inputstrings, arranged from ``most sorted'' to ``least sorted''. Sincetwo strings can be equally sorted, then output them according tothe orginal order.
Sample Input
10 6AACATGAAGGTTTTGGCCAATTTGGCCAAAGATCAGATTTCCCGGGGGGAATCGATGCAT
Sample Output
CCCGGGGGGAAACATGAAGGGATCAGATTTATCGATGCATTTTTGGCCAATTTGGCCAAA
Source
East Central North America 1998
题意:
输入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>
chara[101][101];
intn[101];
int cmp(constvoid*a,constvoid*b)
{
return((*(int*)a-*(int*)b));
}
int main()
{
intr,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);