1. 程式人生 > >二、stl ,模擬,貪心等 [Cloned] J

二、stl ,模擬,貪心等 [Cloned] J

原題:

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.

題意:

對幾串字串進行逆序數大小的排序,逆序數就是數學概念上的逆序數轉化到字母上,例如序列中C在A的前邊那麼逆序數加一。給出的資料只是四種鹼基ACGT,然後按照逆序數從小到大進行排序。

題解:

先定義一個結構體包括一個字串和它的逆序數值,然後一個compare函式對結構體陣列進行排序。重點在於怎麼求一個字串的逆序數,我借鑑了一篇部落格的方法,定義一個四個位置的陣列,然後對字串從後到前進行搜尋,如果是A,那麼陣列的三個位置都加1,因為之前無論出現剩下的哪三個字母逆序數都得加一,如果是C,那麼對應G和T的陣列加一,以此類推,在加陣列的同時統計各個字母對應的逆序數。

程式碼:AC

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef struct
{
	char dna[120];
	int num;
}DNA;
DNA A[120];
bool compare(DNA a,DNA b)
{
	return a.num<b.num;
}
int count(char str[],int len)
{
	int a[4];
	memset(a,0,sizeof(a));
	int sum=0,i;
	for(i=len-1;i>=0;i--)
	{
		switch(str[i])
		{
			case'A':
			{
				a[1]++;
				a[2]++;
				a[3]++;
				break;
			}
			case'C':
			{
				a[2]++;
				a[3]++;
				sum+=a[1];
				break;
			}
			case'G':
			{
				a[3]++;
				sum+=a[2];
				break;
			}
			case'T':
			sum+=a[3];
		}
	}
	return sum;
}
int main()
{
	int n,m,i;
	cin>>n>>m;
	for(i=0;i<m;i++)
	{
		cin>>A[i].dna;
		A[i].num=count(A[i].dna,n);
	}
	sort(A,A+m,compare);
	for(i=0;i<m;i++)
		cout<<A[i].dna<<endl;
	return 0;
}