Text Summary
To solve this problem, condier these four essential points:
- Storing people using a ‘Person’ struct and a two-dimensional vector:
struct Person {
string name;
int height;
};
vector<vector<Person> > ans(k);
- Sorting the ‘Person’ struct based on height and name:
bool cmp(const Person& a, const Person& b) {
if (a.height == b.height)
return a.name < b.name;
else
return a.height > b.height;
}
sort(v.begin(), v.end(), cmp);
- Calculating the number of people in each row:
int column = n / k;
// The last row = column + n % k
- Populating each row with people in a zigzag pattern:
for (i = 0; i < column + n % k and t < n; i++) {
if (i % 2 == 0) ans[0].push_back(v[t++]);
else ans[0].insert(ans[0].begin(), v[t++]);
}
for (i = 1; i < k and t < n; i++) {
for (int j = 0; j < column and t < n; j++){
if (j % 2 == 0) ans[i].push_back(v[t++]);
else ans[i].insert(ans[i].begin(), v[t++]);
}
}
Code Summary
#include <bits/stdc++.h>
using namespace std;
struct Person {
string name;
int height;
};
bool cmp(const Person& a, const Person& b) {
if (a.height == b.height)
return a.name < b.name;
else
return a.height > b.height;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n, k;
cin >> n >> k;
int column = n / k;
vector<Person> v(n);
vector<vector<Person> > ans(k);
int i;
for (i = 0; i < n; i++)
cin >> v[i].name >> v[i].height;
sort(v.begin(), v.end(), cmp);
int t = 0;
for (i = 0; i < column + n % k and t < n; i++) {
if (i % 2 == 0) ans[0].push_back(v[t++]);
else ans[0].insert(ans[0].begin(), v[t++]);
}
for (i = 1; i < k and t < n; i++) {
for (int j = 0; j < column and t < n; j++){
if (j % 2 == 0) ans[i].push_back(v[t++]);
else ans[i].insert(ans[i].begin(), v[t++]);
}
}
for (i = 0; i < k; i++) {
for (int j = 0; j < ans[i].size(); j++) {
if (j) cout << ' ';
cout << ans[i][j].name;
}
cout << endl;
}
}