fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define endl '\n'
  6. #define dtype long long
  7. #define mod 1000000007
  8. #define case(t, c) cout<<"Case "<<t<<":"<<c
  9.  
  10. int main() {
  11. ios_base::sync_with_stdio(false), cin.tie(nullptr);
  12. int t;
  13. cin>>t;
  14. while (t--)
  15. {
  16. int n;
  17. cin>>n;
  18. vector<pair<int,int>>vc(n);
  19. for (auto &i : vc) {
  20. cin>>i.first;
  21. }
  22. vector<vector<int>>vc1(2);
  23. for (auto &i : vc) {
  24. cin>>i.second;
  25. vc1[i.first].emplace_back(i.second);
  26. }
  27. sort(vc1[0].rbegin(),vc1[0].rend());
  28. sort(vc1[1].rbegin(),vc1[1].rend());
  29. int m=min(vc1[0].size(),vc1[1].size());
  30. if(m!=0)
  31. {
  32. vc.clear();
  33. if(vc1[0].size()<vc1[1].size())
  34. {
  35. swap(vc1[1][0],vc1[1][min(m,(int)vc1[1].size()-1)]);
  36.  
  37. int i=0,j=0;
  38. while (i+j<n)
  39. {
  40. if(i<vc1[1].size())
  41. vc.emplace_back(1,vc1[1][i++]);
  42. if(j<vc1[0].size())
  43. vc.emplace_back(0,vc1[0][j++]);
  44. }
  45.  
  46. } else
  47. {
  48. swap(vc1[0][0],vc1[0][min(m,(int)vc1[0].size()-1)]);
  49.  
  50. int i=0,j=0;
  51. while (i+j<n)
  52. {
  53. if(j<vc1[0].size())
  54. vc.emplace_back(0,vc1[0][j++]);
  55. if(i<vc1[1].size())
  56. vc.emplace_back(1,vc1[1][i++]);
  57. }
  58. }
  59.  
  60. }
  61.  
  62. long long cost=vc[0].second;
  63. for (int i = 1; i < n; ++i) {
  64. if(vc[i-1].first!=vc[i].first)
  65. cost+=vc[i].second;
  66. cost+=vc[i].second;
  67. }
  68. cout<<cost<<endl;
  69.  
  70.  
  71.  
  72.  
  73.  
  74. }
  75. return 0;
  76. }
  77.  
  78.  
Success #stdin #stdout 0.01s 5476KB
stdin
4
4
0 1 1 1
1 10 100 1000
6
0 0 0 1 1 1
3 4 5 6 7 8
3
1 1 1
1000000000 1000000000 1000000000
1
1
1
stdout
2112
63
3000000000
1