POJ-1007 DNA Sorting

题目大意:对字符串数组按照逆序数数量进行排序。

题目链接:http://poj.org/problem?id=1007

首先统计每个字符串的逆序数数量,这里采用(n*logn)时间复杂度的二路归并方法(此题n^2复杂度方法貌似也不会超时;鉴于此题字符串只有ATCG四个字母,也可以分别统计每个字母出现次数的前缀和,再一次遍历统计逆序数),然后根据逆序数快排即可。

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>

using namespace std;

#define MAXN 105

struct Entry{
   char str[MAXN];
   int w;
};
Entry a[MAXN];
char s[MAXN];
char tmp[MAXN];

int merge(char* s,int low,int mid,int high)
{
    int i=low;
    int j=mid+1;
    int k=low;
    int count=0;
    while(i<=mid&&j<=high)
    {
        if(s[i]<=s[j])
            tmp[k++]=s[i++];
        else
        {
            tmp[k++]=s[j++];
            count+=j-k;
        }
    }
    while(i<=mid)
        tmp[k++]=s[i++];
    while(j<=high)
        tmp[k++]=s[j++];
    for(i=low;i<=high;i++)
        s[i]=tmp[i];
    return count;
}

int mergeSort(char* s,int a,int b)
{
    if(a<b)
    {
        int mid=(a+b)/2;
        int count=0;
        count+=mergeSort(s,a,mid);
        count+=mergeSort(s,mid+1,b);
        count+=merge(s,a,mid,b);
        return count;
    }
    else return 0;
}

bool cmp(Entry a,Entry b)
{
    return a.w<b.w;
}

int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=0;i<m;i++)
        {
            scanf("%s",a[i].str);
            strcpy(s,a[i].str);
            a[i].w=mergeSort(s,0,n-1);
        }
        sort(a,a+m,cmp);
        for(int i=0;i<m;i++)
        {
            printf("%s\n",a[i].str);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值