题目:编写一个读取程序 n个物品并对它们进行排序。每个物品都有属性{价值,重量,种类,日期,名字},他们分别是 { 整数,整数,大写字母,整数,字符串 }。根据以下优先级对物品进行排序。
首先按价值(升序)
在相等的情况下,按重量(升序)
在相等的情况下,按类型(按字典顺序升序)
在相等的情况下,按日期(升序)
在相等的情况下,按名称(按字典顺序升序)
我的代码:
#include<iostream>
#include<vector>
#include <algorithm>
#include<cstdio>
#include<string.h>
using namespace std;
int zidian(string a, string b) {
int n = a.size();
int m = b.size();
if (n > m) {
n = m;
}
for (int i = 0; i < n; i++) {
if (a[i] < b[i]) {
return 0;
}
else if (a[i] > b[i]) {
return 1;
}
}
}
int main() {
long long int n, d;
cin >> n;
class huowu {
public:
long long int a;
long long int b;
char name;
long long int c;
string date;
bool operator <( huowu q) {
if (this->a > q.a) {
return this->a > q.a;
}
else if (this->a == q.a) {
return this->b > q.b;
}
else if (this->a == q.a && this->b == q.b) {
return this->name > q.name;
}
else if (this->a == q.a && this->b == q.b && this->name == q.name) {
return this->c > q.c;
}
else if (this->a == q.a && this->b == q.b && this->c == q.c && this->name == q.name) {
return zidian(this->date, q.date);
}
else
return false;
}
};
vector<huowu>z(n);
for (int i = 0; i < n; i++) {
cin >> z[i].a;
cin >> z[i].b;
cin >> z[i].name;
cin >> z[i].c;
cin >> z[i].date;
}
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (z[i] < z[j]) {
huowu b;
b = z[i];
z[i] = z[j];
z[j] = b;
}
}
}
for (int i = 0; i < n; i++) {
cout << z[i].a << " " << z[i].b << " " << z[i].name << " " << z[i].c << " " << z[i].date << endl;
}
}
总超时
试试这个 有问题的话建议把输入输出格式给出来 , 都不知道你这个题的输入输出格式是什么
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <string>
using namespace std;
//价值 重量 种类, 日期 名字
//整数 整数 大写字母 整数 字符串
/*
首先按价值(升序)
在相等的情况下,按重量(升序)
在相等的情况下,按类型(按字典顺序升序)
在相等的情况下,按日期(升序)
在相等的情况下,按名称(按字典顺序升序)
*/
struct HuoWu
{
long long int a; //价值
long long int b; //重量
char c; //种类
long long int d; //日期
string e; //名字
bool operator<(const HuoWu& hw)
{
if(this->a != hw.a) return this->a < hw.a;
else if(this->b != hw.b) return this->b < hw.b;
else if(this->c != hw.c) return this->c < hw.c;
else if(this->d != hw.d) return this->d < hw.d;
else return this->e < hw.e;
}
};
int main()
{
long long int n;
cin >> n;
vector<HuoWu> z;
for (int i = 0; i < n; ++i)
{
HuoWu t;
cin>>t.a>>t.b>>t.c>>t.d>>t.e;
z.push_back(t);
}
sort(z.begin(), z.end());
for (int i = 0; i < z.size(); ++i)
{
cout << z[i].a << " " << z[i].b << " " << z[i].c << " " << z[i].d << " " << z[i].e << endl;
}
return 0;
}