Re: [问题] ITSA第24次第4题

楼主: soheadsome (师大狗鼻哥)   2014-05-05 20:02:48
※ 引述《ACMANIAC ()()》之铭言:
: 关于排序,这样写可能会更省时省力,尤其在程式竞赛。
: #include <iostream>
: #include <algorithm>
: #include <string>
: #include <vector>
: using namespace std;
: struct MVP {
: string name;
: int salary, people;
: MVP(const string &name, const int &salary, const int &people) {
: this->name = name;
: this->salary = salary;
: this->people = people;
: }
: bool operator < (const MVP &m) const
: {
: return this->salary > m.salary ||
: this->salary == m.salary && this->people > m.people;
: }
: };
: int main()
: {
: string name;
: int N, S, P;
: cin >> N;
: vector<MVP> m;
: for (int i = 0; i < N && cin >> name >> S >> P; ++i) {
: m.push_back(MVP(name, S, P));
: }
: sort(m.begin(), m.end());
: for (int i = 0; i < N; ++i) {
: if (i) {
: cout << " ";
: }
: cout << m[i].name;
: }
: cout << endl;
: return 0;
: }
: ※ 引述《kkkmode (kkk)》之铭言:
: : 我拿你的code去编译
: : 发现要加#include<string.h> 或 include<cstring>才会编过
: : <cName>是在C++引用C的header<Name.h>的习惯
: : 这题有两个重点:
: : 1.先排序不重要的index再排序重要的
: : 2.如何用标准库排序自定义类型
: : 以下是我改写的code,可以参考一下
: : #include <iostream>
: : #include <vector>
: : #include <algorithm>
: : #include <functional>
: : #include <string>
: : using namespace std;
: : struct playerInfo
: : {
: : int salary;
: : int fans;
: : string name;
: : };
: : bool by_salary(const playerInfo& p1,const playerInfo& p2)
: : {
: : return p1.salary > p2.salary;
: : }
: : bool by_fans(const playerInfo& p1,const playerInfo& p2)
: : {
: : return p1.fans > p2.fans;
: : }
: : int main(){
: : vector<playerInfo > playerList;
: : unsigned int size=0;
: : cin>>size;
: : for(int i=0;i<size;i++) //input player's information
: : {
: : playerInfo temp;
: : cin>>temp.name>>temp.salary>>temp.fans;
: : playerList.push_back(temp);
: : }
: : sort(playerList.begin(),playerList.end(),by_fans);
: : sort(playerList.begin(),playerList.end(),by_salary);
: : for(int i=0;i<size;i++) //output player's information
: : cout<<playerList[i].name<< (i<size-1 ? ' ':'\n');
: : return 0;
: : }
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
struct MVP {
string name;
int salary, people;
inline bool operator <(const MVP &m) const {
return this->salary > m.salary
|| (this->salary == m.salary && this->people > m.people);
}
};
inline istream& operator>> (istream& in, MVP& mvp)
{
return in >> mvp.name >> mvp.salary >> mvp.people;
}
int main() {
int N;
cin >> N;
istream_iterator<MVP> iiter(cin),eos;
vector<MVP> m(iiter,eos);
sort(m.begin(), m.end());
for (int i = 0; i < N; ++i)
cout<< char(!!i * ' ') << m[i].name;
cout << endl;
return 0;
}
帮忙简化一下 不过有些地方是懒人偷吃步 尽量少用...
作者: ACMANIAC (請肥宅救救肥宅)   2014-05-05 20:33:00
连 !! 都出现了 XDD我不懂 <iterator>,想请教一下,这篇的用法是无视题目给的 N 笔资料吗?如果加进去要如何写?谢谢
楼主: soheadsome (师大狗鼻哥)   2014-05-05 21:57:00
加进去就用上一篇的做法吧...

Links booklink

Contact Us: admin [ a t ] ucptt.com