1198: DNA Sorting

来源:互联网 发布:c 程序员简历 编辑:程序博客网 时间:2024/05/22 01:09

题目

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 sequenceAACEDGG” 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'', frommost 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'' toleast 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


代码块

//判断每个字符串的逆序数 然后按照逆序数排序,同时更换,字符串数组里的排序,即可

import java.util.Arrays;import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner cn = new Scanner(System.in);        int a = cn.nextInt();        int b = cn.nextInt();        String[] str = new String[b];        int[][] num = new int[b][a];        for(int i =0;i<b;i++){            str[i] = cn.next();            for(int j =0;j<str[i].length();j++){                for(int k =j+1;k<str[i].length();k++){                    if(str[i].charAt(j)>str[i].charAt(k))                        num[i][j]++;                }            }        }        int[] tem = new int[b];        Arrays.fill(tem, 0);        for(int i =0;i<b;i++){            for(int j =0;j<a;j++){                tem[i]+=num[i][j];            }        }        for(int i =0;i<b;i++){            for(int j =i+1;j<b;j++){                if(tem[i]>tem[j]){                    String temp = str[j];                    str[j] =str[i];                    str[i] = temp;                    int z = tem[j];                    tem[j]= tem[i];                    tem[i] = z;                }            }        }        for(int i =0;i<b;i++){            System.out.println(str[i]);        }    }}