1. 程式人生 > >STL c++ algorithm--sort

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應用,排序後進行相似比的匹配,注意三角性的構成條件即可!