您的位置:首页 > 其它

POJ 1007 DNA排序求逆序数

2011-12-21 00:27 295 查看
基本思路就是求逆序数然后根据逆序数排序,出现的问题有:
1、这题出现的问题主要是对m和n总是搞混,而且提交出现了Runtime Error,这个错误一般都是由于一般都是非法访问内存(数组越界、访问空指针、堆栈溢出)、做除法时除以了0 等造成的,后来仔细看了一下“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. ”就立刻发现了错误,结构体数组开小了。。。

2、求逆序数有O(N^2)的直接比较法和O(NlogN)的分治法,我这里用了比较挫的直接比较法,但也没有超时。模板里面的函数还是慎用为好,否则出现错误了调试有困难。

3、排序用了qsort,对于字符串与逆序数可以用map存,也可以用结构体数组排序,比较函数

int cmp(const void * a,const void * b){

struct sorti * p = (struct sorti *)a;

struct sorti * q = (struct sorti *)b;

return p->count – q->count;

}

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

struct sorti{
	char s[51];
	int count;
} st[101];

int cmp(const void * a,const void * b){
	struct sorti * p = (struct sorti *)a;
	struct sorti * q = (struct sorti *)b;
	return p->count - q->count;
}

int inv(int n,char a[]){
	int ret=0,i,j;
	for(i=0;i<n ;i++){
		for(j=i+1;j<n;j++){
			if(a[j] < a[i]) ret++;
		}
	}
	return ret;
}

int main(){
	int n,m,i;
	cin>>m>>n;
	for(i=0;i<n;i++){
		scanf("%s",st[i].s);
	}
	for(i=0;i<n;i++){
		st[i].count=inv(m,st[i].s);
	}
	qsort(st,n,sizeof(st[0]),cmp);
	for(i=0;i<n;i++){
		printf("%s\n",st[i].s);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: