Created
January 29, 2015 05:25
-
-
Save sturgle/bf7fa6bd715588066bc9 to your computer and use it in GitHub Desktop.
A[i] < A[j] && i < j, then A[i] has a surpasser A[j], calc the max surpasser inside an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <stack> | |
#include <sstream> | |
using namespace std; | |
struct NumExt { | |
int val; | |
int index; | |
int spCnt; | |
NumExt(int _val, int _index, int _cnt): val(_val), index(_index), spCnt(_cnt) {} | |
}; | |
void mergeSortEx(vector<NumExt> &numext, int left, int right) { | |
if (left >= right) { | |
return; | |
} | |
int mid = (left + right) / 2; | |
mergeSortEx(numext, left, mid); | |
mergeSortEx(numext, mid + 1, right); | |
vector<NumExt> tmpArr; | |
int lower = left; | |
int upper = mid + 1; | |
while (lower <= mid && upper <= right) { | |
if (numext[lower].val < numext[upper].val) { | |
tmpArr.push_back(numext[upper++]); | |
} else { | |
numext[lower].spCnt += upper - mid - 1; | |
tmpArr.push_back(numext[lower++]); | |
} | |
} | |
while (lower <= mid) { | |
numext[lower].spCnt += upper - mid - 1; | |
tmpArr.push_back(numext[lower++]); | |
} | |
while (upper <= right) { | |
tmpArr.push_back(numext[upper++]); | |
} | |
for (int i = 0; i < tmpArr.size(); i++) { | |
numext[left + i] = tmpArr[i]; | |
} | |
} | |
int maxSupasser(vector<int> &num) { | |
vector<NumExt> numext; | |
for (int i = 0; i < num.size(); i++) { | |
NumExt tmp(num[i], i, 0); | |
numext.push_back(tmp); | |
} | |
mergeSortEx(numext, 0, numext.size() - 1); | |
int maxIdx = 0; | |
int maxCnt = 0; | |
for (int i = 0; i < numext.size(); i++) { | |
cout << numext[i].val << ": " << numext[i].spCnt << ", "; | |
if (numext[i].spCnt > maxCnt) { | |
maxCnt = numext[i].spCnt; | |
maxIdx = numext[i].index; | |
} | |
} | |
cout << endl; | |
return maxIdx; | |
} | |
int main() { | |
// int vv[7] = {1, 2, 3, 4, 5, 6, 7}; | |
// int vv[7] = {7, 6, 5, 4, 3, 2, 1}; | |
// int vv[7] = {4, 3, 2, 1, 7, 6, 5}; | |
// int vv[7] = {6, 4, 2, 1, 3, 5, 7}; | |
int vv[7] = {6, 4, 2, 3, 1, 5, 7}; | |
vector<int> v(&vv[0], &vv[0] + 7); | |
int i = maxSupasser(v); | |
cout << v[i] << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment