STL c++ algorithm--sort

头文件#include<algorithm>

常用sort函数:默认为升序序列         时间复杂度O(nlog2n)

1)sort()             //排序      

2参数:sort(begin,end)、3参数:sort(begin,end,compare)     //compare为比较规则

//begin为起始位置,end为终止位置,对区间[begin,end-1]内的元素进行排序

2)stable_sort()   //稳定排序

常用的比较函数

bool compare(int a,int b){
     return a>b;//降序
}
bool compare(int a,int b){
     return a<b;//升序
}

简单字符串排序

Time Limit: 5000 ms Memory Limit: 100000 KiB

Problem Description

从键盘输入10个学生的姓名和成绩,请按字典序排列学生的姓名并输出(姓名和成绩对应关系保持不变)。

Input

输入共11行,前10行每行是一个学生的姓名,最后一行是10个用空格分开的整数表示对应的10个学生成绩。(姓名大小不超过20个字符)

Output

输出姓名按字典序排列后的学生姓名和成绩,共10行,每个学生的姓名和成绩占一行,姓名和成绩间用逗号分开。

Sample Input

Bush
White
Mark
Jean
Black
Wood
Jenny
Frank
Bill
Smith
78 85 96 65 46 83 77 88 54 98

Sample Output

Bill,54
Black,46
Bush,78
Frank,88
Jean,65
Jenny,77
Mark,96
Smith,98
White,85
Wood,83
#include<iostream>
#include<algorithm>
#include<string.h>
#define N 105
using namespace std;
typedef struct{
	char name[N];
	int score;
}Student;
bool compare(Student a,Student b){
     if(strcmp(a.name,b.name)<0){
     	return true;
     }
     return false;
}
int main(){
	Student man[10];
	for(int i=0;i<10;i++){
		cin>>man[i].name;
	}
	for(int i=0;i<10;i++){
		cin>>man[i].score;
	}
	stable_sort(man,man+10,compare);
	for(int i=0;i<10;i++){
		cout<<man[i].name<<',';
		cout<<man[i].score<<endl;
	}
	return 0;
}

相似三角形

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

给出两个三角形的三条边,判断是否相似。

Input

多组数据,给出6正个整数,a1,b1,c1,a2,b2,c2,分别代表两个三角形。(边长小于100且无序

Output

如果相似输出YES,如果不相似输出NO,如果三边组不成三角形也输出NO。

Sample Input

1 2 3 2 4 6
3 4 5 6 8 10
3 4 5 7 8 10

Sample Output

NO
YES
NO
#include<iostream>
#include<algorithm>
#include<stdio.h>
#define N 7
using namespace std;
double a[N];
double b[N];
int flag = 1;
bool Check(double a[], double b[], double fag) {
    for(int i = 1; i < 3; i++) {
        if(a[i] / b[i] != fag)
            return false;
    }

    return true;
}
bool R(double a[]) {
    if(a[0] + a[1] > a[2]) {
        return true;
    }

    return false;
}
int main() {
    while(flag) {
        for(int i = 0; i < 3; i++) {
            if(cin >> a[i]) {
                flag = 1;
            } else {
                flag = 0;
            }
        }

        for(int i = 0; i < 3; i++) {
            cin >> b[i];
        }

        if(flag) {
            if(R(a) && R(b)) {
                sort(a, a + 3);
                sort(b, b + 3);

                if(Check(a, b, a[0] / b[0])) {
                    printf("YES\n");
                } else {
                    printf("NO\n");
                }
            } else {
                printf("NO\n");
            }
        }
    }

    return 0;
}
简单的sort应用,排序后进行相似比的匹配,注意三角性的构成条件即可!


猜你喜欢

转载自blog.csdn.net/m0_37848958/article/details/80248394