[POJ_1007] DNA Sorting

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;


const int TEMP_SIZE = 1024;
char temp_buffer[TEMP_SIZE];


void print_array(char* array, int size)
{
	for (int i=0; i<size; i++)
		cout << array[i] << " ";
	cout << endl;
}

// use merge sort to calculate the reverse count
class DNAString
{
public:
	DNAString()
	{
		mInverseCount = 0;
		mData = 0;
		mSize = 0;
	}


	void Allocate(int size)
	{
		mData = new char[size+1];
		mCopy = new char[size+1];
		mSize = size;
	}


	void Read()
	{
		cin >> mData;
		memcpy(mCopy, mData, mSize);
	}


	void Write()
	{
		mCopy[mSize] = 0;
		cout << mCopy << endl;
	}


	bool operator < (const DNAString& other)
	{
		return mInverseCount < other.mInverseCount;
	}


	void Deallocate()
	{
		if (mData)
			delete[] mData;


		if (mCopy)
			delete[] mCopy;
	}


	void CalculateReverseCount()
	{
		MergeSort(0, mSize-1);
	}


private:
	void MergeSort(int start, int end)
	{
		if (start < end)
		{
			int mid = start + (end - start) / 2;
			MergeSort(start, mid);
			MergeSort(mid+1, end);


			Merge(start, mid, end);
		}
	}


	void Merge(int start, int mid, int end)
	{
		int i = start, j = mid+1;
		int temp_idx = i;
		while (i <= mid && j <= end)
		{
			if (mData[j] < mData[i])
			{
				temp_buffer[temp_idx] = mData[j];
				j++;
				temp_idx++;
				mInverseCount += (mid - i + 1);
			}
			else
			{
				temp_buffer[temp_idx] = mData[i];
				i++;
				temp_idx++;
			}
		}




		while (i<=mid)
		{
			temp_buffer[temp_idx] = mData[i];
			i++;
			temp_idx++;
		}




		while (j<=end)
		{
			temp_buffer[temp_idx] = mData[j];
			j++;
			temp_idx++;
		}
		// copy back
		memcpy(&mData[start], &temp_buffer[start], sizeof(char) * (end-start+1));
	}


private:
	int mInverseCount;
	char* mData;
	char* mCopy;
	int mSize;
};




int main()
{
	int m, n;
	cin >> n >> m;


	vector<DNAString> vStrs;


	for (int i=0; i<m; i++)
	{
		vStrs.push_back(DNAString());
		vStrs[i].Allocate(n);
		vStrs[i].Read();
		vStrs[i].CalculateReverseCount();
	}


	sort(vStrs.begin(), vStrs.end());


	for (int i=0; i<m; i++)
	{
		vStrs[i].Write();
//		vStrs[i].Deallocate();
	}


	return 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值