PAT A1109 Group Graph C++ solution

1. Idea

  • Sort everyone from high to low (struct implementation)
  • A total of k lines are to be output, each line outputs m people, and m is discussed, the first line m = n/k + n%k, and the rest of the lines are m = n/k
  • Traverse the sorted stu structure, output m in each line
  • For each row, use two vectors: left and right, respectively store the person standing on the left and the person on the right, then print left first, then print right

2. Code (C++)

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
using namespace std;

struct Student{
  string name;
  int height;
}stu[10010];

bool cmp(Student a, Student b)
{
  if(a.height != b.height) return a.height > b.height;
  else return strcmp(a.name.c_str(), b.name.c_str()) < 0;
}

int main(){
  int n, k;
  scanf("%d%d", &n, &k);
  for(int i = 1; i <= n; i++)
  {
    cin>>stu[i].name>>stu[i].height;
  }
  sort(stu+1, stu+n+1, cmp);

  int m;
  int start = 1, end = 0;
  for(int i = 1; i<=k; i++)
  {
    if(i == 1)
    {
      m = n/k + n%k;
      end  = m;
    }
    else
    {
      m = n/k;
      end += m;
    }
    int mid = (start + end) / 2 + 1;
    vector<string> left;
    vector<string> right;
    right.push_back(stu[start].name);
    start++;
    while(start <= end)
    {
      if(start <= end)
      {
        left.push_back(stu[start].name);
        start++;
      }
      if(start <= end)
      {
        right.push_back(stu[start].name);
        start++;
      }
    }
    bool is_left = false;
    for(int j = left.size()-1; j >=0; j--)
    {
      if(j != left.size() - 1) printf(" ");
      cout<<left[j];
      is_left = true;
    }
    for(int j = 0; j < right.size(); j++)
    {
      if(is_left)
      printf(" ");
      cout<<right[j];
    }
    if(i != k)
    printf("\n");

  }
  
  return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45203752/article/details/126375305