# CodeTop原创题题解（部分）

#### 第一题

// 最少抽牌次数
int shuffle_cards(vector<int>& cards) {
int n = cards.size(), pre = n, cnt = 0;
for(int i = n-1;i >= 0;i--) {
if(cards[i] == pre) {
pre--;
cnt++;
}
}
return n-cnt;
}


#### 第二题

#include<iostream>
#include<cstdio>
#include<vector>
#include<random>
#include<time.h>
using namespace std;

struct Comparator {
int operator()(const string& s1_, const string& s2_) const{
string s1 = s1_, s2 = s2_;    // copy, because operator() is const
if(s1 == s2)  return 0;
return s1 < s2 ? -1 : 1;
// return s1 < s2;
}
};

int split(vector<string>& NorB, string pivot, Comparator compare, int start, int end){
int i = start;
string temp = NorB[start];
for(int j = i+1; j <= end; j++) {
if(compare(NorB[j], pivot) == -1) {  // 小于
i++;
swap(NorB[i], NorB[j]);
}
if(compare(NorB[j], pivot) == 0) {  // 相等
swap(NorB[j], NorB[start]);
j--;
}
}
swap(NorB[start], NorB[i]);
return i;
}

void quicksort(vector<string>& nuts, vector<string>& bolts, Comparator compare, int start, int end){
if(start >= end) return;
int index = split(nuts, bolts[start], compare, start, end);
split(bolts, nuts[index], compare, start, end);
quicksort(nuts, bolts, compare, start, index-1);
quicksort(nuts, bolts, compare, index+1, end);
}

void sortNutsAndBolts(vector<string> &nuts, vector<string> &bolts, Comparator compare) {
int n = nuts.size();
quicksort(nuts, bolts, compare, 0, n-1);
}

int main() {
Comparator compare;
// cout << compare("ab", "AB") << endl;
// cout << compare("ab", "CD") << endl;
// cout << compare("ef", "CD") << endl;
vector<string> nuts = {"ab", "cd", "ef", "gh", "ij", "kl", "mn", "op", "qr", "st", "uv", "wx", "yz"};
vector<string> bolts = {"AB", "CD", "EF", "GH", "IJ", "KL", "MN", "OP", "QR", "ST", "UV", "WX", "YZ"};
shuffle(bolts.begin(), bolts.end(), default_random_engine(time(0)));  // 打乱一个就可以了
// shuffle(nuts.begin(), nuts.end(), default_random_engine(time(0)));  // 由于随机种子相同，打乱两个会一模一样
for(int i = 0; i < nuts.size(); i++) {
cout << nuts[i] << " " << bolts[i] << endl;
}
cout << "************" << endl;
sortNutsAndBolts(nuts, bolts, compare);
for(int i = 0; i < nuts.size(); i++) {
cout << nuts[i] << " " << bolts[i] << endl;
}
}

posted @ 2021-12-28 15:39  Rogn  阅读(151)  评论(0编辑  收藏  举报