dfs判断联通块
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define int long long
#define INF 0x3f3f3f3f
const int N = 1e5 + 10, M = 2e5 + 10;
int n, m;
int h[N], e[M], ne[M], idx;
bool st[N];
int x1, y1, x2, y2;
vector<pair<int, int>> pos;
void add(int a, int b) // 添加一条边a->b
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u)
{
st[u] = true;
x1 = min(x1, pos[u].first);
x2 = max(x2, pos[u].first);
y1 = min(y1, pos[u].second);
y2 = max(y2, pos[u].second);
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j])
dfs(j);
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
memset(h, -1, sizeof(h));
cin >> n >> m;
pos.push_back({0, 0}); // 优化
for (int i = 1; i <= n; ++i)
{
int x, y;
cin >> x >> y;
pos.push_back({x, y});
}
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
int res = INF;
for (int i = 1; i <= n; ++i)
{
if (!st[i])
{
x1 = INF, y1 = INF, x2 = 0, y2 = 0;
dfs(i);
res = min((x2 - x1) * 2 + (y2 - y1) * 2, res);
}
}
cout << res << endl;
return 0;
}