蒟蒻调了半天没调出来。
#include <iostream>
#include <cctype>
#include <algorithm>
#define ll long long
using namespace std;
ll read()
{
ll x = 0, f = 1;
char ch = 0;
while (!isdigit(ch))
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (isdigit(ch))
{
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
const int maxN = 5e5 + 10;
ll T;
ll n, m;
ll ans;
struct node
{
ll a, b, c;
} p[maxN];
bool cmp(node a, node b)
{
return a.c > b.c;
}
int main()
{
T = read();
while (T--)
{
ans = 0;
n = read(), m = read();
for (int i = 1; i <= n; i++)
{
p[i].a = read(), p[i].b = read();
p[i].c = p[i].b - p[i].a;
}
sort(p + 1, p + 1 + n, cmp);
ll now = 1;
while (now <= m - n && p[now].c > 0 && now <= n)
ans += p[now++].b;
if (now == n)
{
if (p[now - 1].a + p[now].a < p[now - 1].b + p[now].b)
ans += p[now].b;
else
ans = ans - p[now - 1].b + p[now - 1].a + p[now].a;
}
else if (now < n)
for (int i = now; i <= n; i++)
ans += p[i].a;
printf("%lld\n", ans);
}
return 0;
}