が小さいのでバブルソートなどの 時間アルゴリズムでも間に合うが,ここでは,C++ の STL にある std::sort
アルゴリズムを使用する.
番目のレストランの情報を3個組 として持ち, std::sort
に適用すると 時間で要求される順番に整列される.3個組をどのようにデータとして表現するかで実装方法がいろいろあるが,下では構造体による実装,STL の <pair>
による実装,STL の <tuple>
による実装と ラムダ式 を用いた実装を載せる.
計算時間:
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0); ios::sync_with_stdio(false);
int n;
cin >> n;
struct Restaurant {
string city;
int score, id;
bool operator<(const Restaurant &rhs) {
return (this->city < rhs.city) ||
(this->city == rhs.city && this->score >= rhs.score);
}
};
vector<Restaurant> rs(n);
for (int i = 0; i < n; ++i) {
cin >> rs[i].city >> rs[i].score;
rs[i].id = i + 1;
}
sort(rs.begin(), rs.end());
for (const auto &r : rs)
cout << r.id << '\n';
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0); ios::sync_with_stdio(false);
int n;
cin >> n;
vector<pair<pair<string, int>, int>> rs(n);
for (int i = 0; i < n; ++i) {
cin >> rs[i].first.first >> rs[i].first.second;
rs[i].first.second *= -1;
rs[i].second = i + 1;
}
sort(rs.begin(), rs.end());
for (const auto &r : rs)
cout << r.second << '\n';
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0); ios::sync_with_stdio(false);
int n;
cin >> n;
vector<tuple<string, int, int>> rs(n);
for (int i = 0; i < n; ++i) {
cin >> get<0>(rs[i]) >> get<1>(rs[i]);
get<1>(rs[i]) *= -1;
get<2>(rs[i]) = i + 1;
}
sort(rs.begin(), rs.end());
for (const auto &r : rs)
cout << get<2>(r) << '\n';
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0); ios::sync_with_stdio(false);
int n;
cin >> n;
vector<string> city(n);
vector<int> score(n), idx(n);
iota(idx.begin(), idx.end(), 0);
for (int i = 0; i < n; ++i)
cin >> city[i] >> score[i];
sort(idx.begin(), idx.end(), [&city, &score](int i, int j) {
return (city[i] < city[j])
|| (city[i] == city[j] && score[i] >= score[j]);
});
for (int no : idx)
cout << no + 1 << '\n';
return 0;
}
2個組以下ならば迷わないけど3個組以上になると少し迷う.好きな方法で良いと思う.
ラムダ式でキャプチャの参照を const できないのかな?