#include #include #include template using MaxHeap = std::priority_queue; using namespace std; using lint = long long; void solve() { int n, m, k; cin >> n >> m >> k; vector cnt(n, 0), first(n, 0); lint ans = 0; while (m--) { int x; lint y; cin >> x >> y; --x; ++cnt[x]; first[x] += y * 2 - 1; ans += y * y; } MaxHeap> heap; for (int i = 0; i < n; ++i) { heap.emplace(first[i], i); } while (k--) { auto [d, i] = heap.top(); heap.pop(); ans -= d; heap.emplace(d - cnt[i] * 2, i); } cout << ans << "\n"; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int q; cin >> q; while (q--) solve(); return 0; }