排序算法(含字符串处理)

strcpy(),strcmp(),strlen(),这三个都是针对于char类型的数组而言的,可以解决一些字符串的题目。

strcpy()

char arr[10];

strcpy(arr,"hello");

strcmp()

比较两个字符串的大小,int strcmp(const char * str1,const char *str2);

如果第一个比第二个大,返回大于0的数字,第一个等于第二个,返回0,第一个小于第二个,返回小于0的数字。

strlen()

strlen(const char *str);

返回字符串的长度

明明的随机数

#include
using namespace std;
int arr[1001];
int main() {
    iostream::sync_with_stdio(false);
    memset(arr, 0, 1001);
    int n;
    cin >> n;
    int a;
    int num = 0;
    for (int i = 0; i < n; i++) {
        cin >> a;
        arr[a]++;
        num++;
        if (arr[a] > 1)num--;
    }
    cout << num << endl;

    for (int i = 1; i <= 1000; i++) {
        if (arr[i] != 0)cout << i << " ";
    }
    return 0;
}

宇宙总统

#include
using namespace std;
#pragma warning(disable:4996)
int main() {
    iostream::sync_with_stdio(false);
    int n;
    cin >> n;
    char max[105];
    char temp[105];
    cin >> max;
    int number = 1;
    for (int i = 2; i <= n; i++)
    {
        cin >> temp;
        if (strlen(temp) > strlen(max)) {
            strcpy(max, temp);
            number = i;
            continue;
        }
        if (strlen(temp) == strlen(max) && strcmp(temp, max) > 0) {
            strcpy(max, temp);
            number = i;
        }


    }
    cout << number << endl << max;
    return 0;
}

奖学金

#include
using namespace std;

struct student {
    int id;
    int y, s, w;
    int sum;
}s[300];
bool cmp(student s1, student s2) {
    if (s1.sum != s2.sum)return s1.sum > s2.sum;
    else {
        if (s1.y != s2.y) {
            return s1.y > s2.y;
        }
        else {
            return s1.id < s2.id;
        }
    }
}
int main() {
    iostream::sync_with_stdio(false);
    int n;
    cin >> n;
    int yy, ss, ww;
    for (int i = 1; i <= n; i++) {
        cin >> yy >> ss >> ww;
        s[i].id = i;
        s[i].y = yy;
        s[i].s = ss;
        s[i].w = ww;
        s[i].sum = yy + ss + ww;
    }
    sort(s+1, s + n+1, cmp);
    for (int i = 1; i <= 5; i++) {
        cout << s[i].id << " " << s[i].sum << endl;
    }
    return 0;
}

你可能感兴趣的:(ACM_Training,c++,开发语言)