#include <vector>
#include <iostream>
#include <cassert>
using namespace std;
int cmp(pair<int,int> a,pair<int,int> b) {
if(a.second != b.second)
return a.second < b.second;
else
return a.first < b.first;
}
vector<pair<int,int>> best_time(vector<pair<int,int>>forRoute,vector<pair<int,int>>returnRoute,int maxDist) {
sort(forRoute.begin(),forRoute.end(),cmp);
sort(returnRoute.begin(),returnRoute.end(),cmp);
int n1 = forRoute.size();
int n2 = returnRoute.size();
int l = 0,r = n2 - 1;
int tmp_val = 0;
vector<pair<int,int>> temp_ans;
//a[l] + a[r] > maxDist
while(l < n1 && r >= 0) {
// cout << l << "------" << r << "\n";
while (r >= 0 && forRoute[l].second + returnRoute[r].second > maxDist) {
r--;
}
// cout << l << "------" << r << "\n";
int pre_r = n2-1;
if (r >= 0 && forRoute[l].second + returnRoute[r].second > tmp_val) {
tmp_val = forRoute[l].second + returnRoute[r].second;
temp_ans.clear();
pre_r = r;
temp_ans.push_back(make_pair(forRoute[l].first, returnRoute[r].first));
r--;
}
// cout << "pre_r:" << pre_r << "\n";
while (r >= 0 && forRoute[l].second + returnRoute[r].second == tmp_val) {
temp_ans.push_back(make_pair(forRoute[l].first, returnRoute[r].first));
r--;
}
// cout << "43:" << forRoute[l].second << " " << forRoute[l+1].second << "\n";
if(l <= n1-2 && forRoute[l].second == forRoute[l+1].second) {
r = pre_r;
} else if(r < n2 - 1){
r++;
}
if(returnRoute[r].second == returnRoute[pre_r].second) {
r = pre_r;
}
// cout << "r:" << r << "\n";
l++;
}
return temp_ans;
}
int main()
{
vector<pair<int,int>>forRoute;
vector<pair<int,int>>returnRoute;
int a[6] = {0,7,8,14,14,16};
int b[6] = {0,1,5,5,14,14};
int maxDist = 20;
for(int i=1;i<=5;i++){
forRoute.push_back(make_pair(i,a[i]));
returnRoute.push_back(make_pair(i,b[i]));
}
vector<pair<int,int>>ans = best_time(forRoute,returnRoute,maxDist);
for(int i=0;i<ans.size();i++) {
cout << ans[i].first << " " << ans[i].second << "\n";
}
return 0;
}