#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;
}
[POJ_1007] DNA Sorting
最新推荐文章于 2020-03-07 20:20:15 发布