/*
translation:
见小白书p246
solution:
最小费用流
对于一个区间,在a,b之间连上一条容量1,费用w的边,表示选中这个得到w。区间内部点之间i,i+1之间连上一条
容量无穷,费用0的边。每个a与s相连,容量1,费用0。每个b同理。这样建图之、后跑最小费用流即可。
note: *
*/
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 505;
const int INF = 0x3f3f3f3f;
typedef pair P;
struct Edge
{
int to, cap, cost, rev;
Edge(int to_, int cap_, int cost_, int rev_):to(to_),cap(cap_),cost(cost_),rev(rev_){}
};
vector G[maxn];
int V, n, k;
int a[maxn], b[maxn], w[maxn], id[100005];
int h[maxn], dist[maxn], prevv[maxn], preve[maxn];
void add_edge(int from, int to, int cap, int cost)
{
G[from].push_back(Edge(to, cap, cost, G[to].size()));
G[to].push_back(Edge(from, 0, -cost, G[from].size()-1));
}
int min_cost_flow(int s, int t, int f)
{
int res = 0;
while(f > 0) {
fill(dist, dist + V, INF);
dist[s] = 0;
bool update = true;
while(update) {
update = false;
for(int v = 0; v < V; v++) {
if(dist[v] == INF) continue;
for(int i = 0; i < G[v].size(); i++) {
Edge& e = G[v][i];
if(e.cap > 0 && dist[e.to] > dist[v] + e.cost) {
dist[e.to] = dist[v] + e.cost;
prevv[e.to] = v;
preve[e.to] = i;
update = true;
}
}
}
}
if(dist[t] == INF) return -1;
int d = f;
for(int v = t; v != s; v = prevv[v]) {
d = min(d, G[prevv[v]][preve[v]].cap);
}
f -= d;
res += d * dist[t];
for(int v = t; v != s; v = prevv[v]) {
Edge& e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}
int main()
{
//freopen("in.txt", "r", stdin);
int T;
scanf("%d", &T);
while(T--) {
for(int i = 0; i < maxn; i++) G[i].clear();
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i++) {
scanf("%d%d%d", &a[i], &b[i], &w[i]);
}
vector pos;
for(int i = 0; i < n; i++) {
pos.push_back(a[i]);
pos.push_back(b[i]);
}
sort(pos.begin(), pos.end());
pos.erase(unique(pos.begin(), pos.end()), pos.end());
memset(id, 0, sizeof(id));
for(int i = 0; i < pos.size(); i++) id[pos[i]] = i;
int s = pos.size(), t = s + 1;
for(int i = 0; i < n; i++) {
add_edge(id[a[i]], id[b[i]], 1, -w[i]);
add_edge(s, id[a[i]], 1, 0);
add_edge(id[b[i]], t, 1, 0);
}
for(int i = 0; i < pos.size()-1; i++) {
add_edge(i, i + 1, INF, 0);
}
add_edge(s, 0, k, 0); add_edge(pos.size() - 1, t, k, 0);
V = t + 1;
printf("%d\n", -min_cost_flow(s, t, k));
}
return 0;
}