fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. int tests;
  8. cin>>tests;
  9. while(tests--) {
  10. vector<pair<int,int>> books;
  11. vector<int> smallest;
  12. int prev=-1;
  13. long long curr=0;
  14. long long rem=0;
  15. long long total=0;
  16. int num;
  17. cin>>num;
  18. for(int i=0;i<num;i++) {
  19. int auth,happ;
  20. cin>>auth>>happ;
  21. books.push_back(make_pair(auth,happ));
  22. }
  23. sort(books.begin(),books.end()); //Groups books by same author together. Within the same groups, books are sorted from smallest happiness to largest happiness.
  24. for(const auto& book : books) {
  25. if(book.first==prev) {
  26. rem+=book.second;
  27. } else {
  28. smallest.push_back(book.second);
  29. prev=book.first;
  30. }
  31. }
  32. //pick smallest book from each author
  33. sort(smallest.begin(),smallest.end()); //sort these books from smallest to largest.
  34. for(const auto& small:smallest) {
  35. total+=(++curr)*small;
  36. }
  37. total+=rem*curr;
  38. cout<<total<<'\n';
  39. }
  40. return 0;
  41. }
Success #stdin #stdout 0s 4244KB
stdin
2
3
3 4
1 2
3 3
4
1 6
2 4
2 3
1 8
stdout
16
39