PAT A1109 Group Photo(25 分)
1.這道題初看題意複雜,其實很簡單的排序問題。
2.要注意用vector的時候一定不要多給,少給了會vector out of ....,但多給了不容易看出來,要多少給多少,我就是因為多給了導致排序出來得結果有兩個空node
程式碼:
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct node{
string name;
int high;
};
vector<int> row;
vector<node> sp;
vector<vector<string> > a;
bool cmp(node a,node b)
{
if (a.high != b.high)return a.high < b.high;
else{
return a.name > b.name;
}
}
int main()
{
int n, k;
cin >> n >> k;
row.resize(k+2);
int per = n / k;
int last = n - per*(k - 1);
for (int i = 1; i <= k; i++)
{
if (i != k)row[i] = per;
else row[i] = last;
}
sp.resize(n);
for (int i = 0; i < n; i++)
{
cin >> sp[i].name >> sp[i].high;
}
sort(sp.begin(), sp.end(), cmp);
int max1 = n - 1;
a.resize(k+5);
for (int i = k; i >= 1; i--)
{
a[i].resize(row[i]+5);
int p = row[i] / 2; p++;//最佳位置
int peo = row[i];//人數
int sq = peo; //判斷
if (p >= 1 && p <= peo){
a[i][p] = sp[max1--].name; sq--;
}
int s = 1;
while (sq>0)
{
if (p - s >= 1){ a[i][p - s] = sp[max1--].name; sq--; }
if (p + s <= peo){ a[i][p + s] = sp[max1--].name; sq--; }
s++;
}
}
for (int i = k; i >= 1; i--)
{
for (int j = 1; j <= row[i]; j++)
{
cout << a[i][j];
if (j != row[i])cout << " ";
}
if (i != 1)cout << endl;
}
return 0;
}