插入排序练习题/sort函数练习
// codingEx.cpp : Defines the entry point for the console application.
// author: momogary1204
#include "stdafx.h"
#include<iostream>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
const int MAX_NUM = 1000;
//插入排序
void insertSort(int* array,const int& len){
for (int i = 1; i < len; i++){
int k = i;
int tmp = array[i];
for (int j = i - 1; j>=0; j--){
if (array[j] < tmp){
k = j;
array[j + 1] = array[j];
}
else{
k = j+1;
break;
}
}
if (k != i)
array[k] = tmp;
}
}
int calNum(const int* array, const int& len,const int& needs){
int sum = 0;
bool flag = false;
int num = 0;
for (int i = 0; i < len; i++){
sum += array[i];
if (sum >= needs){
num = i + 1;
flag = true;
break;
}
}
return flag ? num : -1;
}
int calNum(const vector<int> array, const int& len, const int& needs){
int sum = 0;
bool flag = false;
int num = 0;
for (int i = 0; i < len; i++){
sum += array[i];
if (sum >= needs){
num = i + 1;
flag = true;
break;
}
}
return flag ? num : -1;
}
bool larger(int a, int b){
return a > b;
}
int main()
{
int scenNum = 0;
cin >> scenNum;
int needs = 0, friends = 0;
//int array[MAX_NUM];
vector<int> result;
while (scenNum--){
cin >> needs >> friends;
int number;
vector<int> array;
for (int i = 0; i < friends; i++){
//cin >> array[i];
cin >> number;
array.push_back(number);
}
//insertSort(array, friends);
sort(array.begin(), array.end(), larger);
result.push_back(calNum(array, friends, needs));
}
for (int i = 0; i < result.size(); i++){
cout << "Scenario #" << i + 1 << ":" << endl;
if (result[i] == -1)
cout << "impossible" << endl;
else
cout << result[i] << endl;
//cout << (result[i] == -1 ? "impossible" : result[i]) << endl;
cout << endl;
}
return 0;
}