fork download
  1. #include <iostream>
  2. #include<bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. bool sortinrev(const pair<int,int> &a,
  7. const pair<int,int> &b)
  8. {
  9. return (a.first > b.first);
  10. }
  11.  
  12. int main() {
  13.  
  14. int i,j,n,t;
  15. cin>>t;
  16. while(t--){
  17. cin>>n;
  18. long long int x;
  19. vector< pair <long long int,int> > vect;
  20. for(i=0;i<n;i++)
  21. for(j=0;j<n;j++){
  22. cin>>x;
  23. vect.push_back( make_pair(x,i) );
  24.  
  25. }
  26.  
  27. sort(vect.begin(), vect.end(), sortinrev);
  28.  
  29. int n1=n-1;
  30. long long int res=0;
  31. for(i=0;i<n*n;i++){
  32. if(vect[i].second==n1){
  33. res+=vect[i].first;
  34. n1--;
  35. if(n1<0)
  36. break;
  37. }
  38. }
  39. if(n1<0)
  40. cout<<res<<endl;
  41. else
  42. cout<<"-1\n";
  43.  
  44. }
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 4180KB
stdin
1
5
5 5 5 5 5
5 5 5 5 5
24 45 85 69 58
6 6 6 6 666
88888 6 6 6 6
stdout
89649