C++算法问题求助非常感谢非常感谢

2个回答

stl library怎么被翻译成“STL图书馆”

int function(string * arr, int n)
{
int x = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] != arr[x]) arr[++x] = arr[i];
}
return x + 1;
}

6 个月之前 回复
JonathanYan 回复贵阳老马马善福专门编写代码的老马就是我！: 你这个是不是只能处理重复名字是连续的情况，比如“Andy Cat Andy Cat”得结果就不对了
6 个月之前 回复

6 个月之前 回复
weixin_45620260 回复: 老马 哈哈哈
6 个月之前 回复
weixin_45620260 多谢了老妈! 刚开始学算法 还是用的C++ 所以还要补很多知识. 太感谢了!!!
6 个月之前 回复

``````#include <iostream>
#include <string>

using namespace std;

typedef struct V{
int index;
string str;
} V;

bool compByStr(V a, V b){
return a.str > b.str;
}

bool compByIndex(V a, V b){
return a.index > b.index;
}

void swap(V &a, V &b){
V temp = a;
a = b;
b = temp;
}

void upHeap(V* s, int size, int index, bool (*comp)(V a, V b)){
int f = index / 2;
while(index){
if(comp(s[f], s[index]))
swap(s[f], s[index]);
else
break;

index = f;
f = index / 2;
}
}

void downHeap(V* s, int size, int index, bool (*comp)(V a, V b)){
int l = index * 2 + 1;
int r = index * 2 + 2;
while(l < size){
int toSwap = l;

if(r<size && comp(s[l], s[r]))
toSwap = r;

if(comp(s[index], s[toSwap]))
swap(s[index], s[toSwap]);
else
break;

index = toSwap;
l = index * 2 + 1;
r = index * 2 + 2;
}
}

void makeHeap(V* s, int size, bool (*comp)(V a, V b)){
for(int i = size/2; i >= 0; i--){
downHeap(s, size, i, comp);
}
}

void pushHeap(V* s, int size, V val, bool (*comp)(V a, V b)){
upHeap(s, size, size, comp);
}

V popHeap(V* s, int size, bool (*comp)(V a, V b)){
V temp = s[0];
s[0] = s[size - 1];
downHeap(s, size - 1, 0, comp);
return temp;
}

int main(){
int n, size, size2 = 0;
cin >> n;
size = n;

V *list = new V[n];
V *list2 = new V[n];
for(int i = 0; i < size; i++){
cin >> list[i].str;
list[i].index = i;
}

makeHeap(list, size, compByStr);

while(size){
V a = popHeap(list, size, compByStr);
if(!size2 || list2[size2-1].str != a.str)
list2[size2++] = a;
size--;
}

makeHeap(list2, size2, compByIndex);

while(size2){
V a = popHeap(list2, size2, compByIndex);
cout << a.str << endl;
size2--;
}

delete[] list;
delete[] list2;

return 0;
}
``````