P2212 [USACO14MAR]Watering the Fields S
思路
最小生成树板子题(水,奈何忘了板子… ,唯一需要注意的是最短边必须大于c , 小于c无法连通。
因为是稠密图,所以用堆优化也优化不了多少。(懒)
记得从i=1,开始读入,因为不存在第0个点这种说法(因为这个,我甚至怀疑过模板,hh)
code
#include<cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int N = 2010, INF = 0x3f3f3f3f;
int n, c;
int x[N], y[N];
int dist[N];
bool st[N];
int dis(int a,int b)
{
if(((x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b]))>=c)
return ((x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b]));
else
return INF;
}
int prim()
{
memset(dist, 0x3f, sizeof dist);
int res = 0;
for (int i = 0; i < n; i ++ )
{
int t = -1;
for (int j = 1; j <= n; j ++ )
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
if (i && dist[t] == INF)
return INF;
if(i)
res += dist[t];
st[t] = true;
for (int j = 1; j <= n; j ++ )
{
if(dist[j]>dis(t,j))
dist[j] = dis(t, j);
}
}
return res;
}
int main()
{
scanf("%d%d", &n, &c);
for (int i = 1; i <= n;i++)
scanf("%d%d", &x[i],&y[i]);
int t = prim();
if (t == INF) puts("-1");
else printf("%d\n", t);
return 0;
}