#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 2e4 + 5;
int v[N], w[N], f[N << 1], p[N], n, m, total, a, b, x;
unordered_map<int, int> ac;
int find(int x)
{
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
cin >> n >> total >> m;
for (int i = 1; i <= n; i++)
p[i] = i;
while (m--)
{
cin >> a >> b, a = find(a), b = find(b);
p[find(a)] = find(b);
}
for (int i = 1; i <= n; i++)
x = find(i), ac[p[x]]++;
for (auto t : ac)
for (int j = total * 2; j >= t.second; j--)
f[j] = max(f[j], f[j - t.second] + t.second);
pair<int, int> res = {1e5 + 5, 1e5 + 5};
for (int i = 0; i <= total * 2; i++)
if (f[i] && abs(i - total) < abs(res.first - total))
res.second = f[i], res.first = i;
else if (abs(i - total) == abs(res.first - total) && f[i] < res.second)
res.first = i, res.second = f[i];
cout << res.second << endl;
}
看讨论区有个双倍经验的题我做过,就把那个题代码拿来改的,45分很奇怪,不太明白哪里出问题了??
这个total*2开始循环是36分,第一个点TLE,total+20000开始循环是45分(不知道为什么+20000反而不TLE了,m的上限是2e4啊)