/* -*- coding: utf-8 -*- * * 1715.cc: No.1715 Dinner 2 - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 1000; const int MAX_D = 1000; const int MAX_P = 100000; const int MAX_PD = MAX_P * MAX_D; const int INF = 1 << 30; /* typedef */ typedef pair pii; /* global variables */ pii pqs[MAX_N]; int ts[MAX_P + 1][2]; /* subroutines */ bool check(int d, int maxp, int x) { int s = 0, ci = -1; while (d--) { int p = min(maxp, x - s); if (ts[p][0] != -1 && ts[p][0] != ci) { ci = ts[p][0]; s -= pqs[ci].second; } else if (ts[p][1] != -1 && ts[p][1] != ci) { ci = ts[p][1]; s -= pqs[ci].second; } else return false; if (s > x) return false; } return true; } /* main */ int main() { int n, d; scanf("%d%d", &n, &d); int maxp = 0; for (int i = 0; i < n; i++) { int pi, qi; scanf("%d%d", &pi, &qi); pqs[i] = pii(pi, -pi + qi); maxp = max(maxp, pi); } sort(pqs, pqs + n); memset(ts, -1, sizeof(ts)); int mxq0 = -INF, mxq1 = -INF, mxi0 = -1, mxi1 = -1; for (int p = 1, i = 0; p <= maxp; p++) { while (i < n && pqs[i].first <= p) { if (mxq0 < pqs[i].second) mxq1 = mxq0, mxi1 = mxi0, mxq0 = pqs[i].second, mxi0 = i; else if (mxq1 < pqs[i].second) mxq1 = pqs[i].second, mxi1 = i; i++; } ts[p][0] = mxi0, ts[p][1] = mxi1; //printf("%d,%d ", ts[p][0], ts[p][1]); } //putchar('\n'); int x0 = 0, x1 = maxp * d; while (x0 + 1 < x1) { int x = (x0 + x1) / 2; if (check(d, maxp, x)) x1 = x; else x0 = x; } printf("%d\n", -x1); return 0; }