poj 1007:DNA Sorting(水题,字符串逆序数排序)

时间:2022-07-15 17:19:02
DNA Sorting
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 80832   Accepted: 32533

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的字符串,要求让你按照字符串的逆序数进行稳定排序。
    所谓逆序数,就是给定一个排列和一个标准次序,如果这个排列中有两个元素与标准次序不同,则称这是一个逆序,这个排列的所有逆序总数称为这个排列的逆序数。
  思路:定义一个结构体存储字符串和字符串的逆序数,在主程序里,输入字符串之后计算每一个字符串的逆序数。然后用sort进行排序,最后输出排序后的字符串。
  代码
 #include <iostream>
#include <algorithm>
using namespace std;
struct Str{
char s[];
int n; //逆序数个数
};
bool cmp(const Str &a,const Str &b)
{
if(a.n<b.n)
return ;
return ;
}
int main()
{
int n,m,i,j;
Str str[];
while(cin>>n>>m){
for(i=;i<=m;i++) //输入
cin>>str[i].s;
for(i=;i<=m;i++){
int num=;
int A=,C=,G=;
for(j=n-;j>=;j--){
switch(str[i].s[j]){ //计算逆序数
case 'A':A++;break;
case 'C':C++;num+=A;break;
case 'G':G++;num+=A;num+=C;break;
case 'T':num+=A;num+=C;num+=G;break;
default:break;
}
}
str[i].n = num;
}
sort(str+,str+m+,cmp);
for(i=;i<=m;i++)
cout<<str[i].s<<endl;
}
return ;
}

Freecode : www.cnblogs.com/yym2013