题目链接
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define N 1000010
using namespace std;
struct node
{
int a;//端点1
int b;//端点2
int num;//权值
};
bool cmp(node x,node y)//按权值升序
{
return x.num<y.num;
}
int maps[1003][1003];
node edge[N*2];//边数=2mn-m-n<2mn
int father[N];
int r[N];
int finds(int x)
{
if(father[x]!=x)
father[x]=finds(father[x]);
return father[x];
}
void connect(int a,int b)
{
if(r[a]>r[b])
father[b]=a;
else if(r[a]<r[b])
father[a]=b;
else
{
father[a]=b;
r[b]++;
}
}
int main()
{
int T,cas=1,n,m,ans,id;
int i,j;
scanf("%d",&T);
while(T--)
{
int numedge=0;//边数
ans=0;
memset(r,0,sizeof(r));
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
scanf("%d",&maps[i][j]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
id=(i-1)*m+j;
father[id]=id;
if(i<n)//除最后一行外
{
numedge++;
edge[numedge].a=id;
edge[numedge].b=i*m+j;
edge[numedge].num=abs(maps[i][j]-maps[i+1][j]);
}
if(j<m)//除最后一列外
{
numedge++;
edge[numedge].a=id;
edge[numedge].b=(i-1)*m+j+1;
edge[numedge].num=abs(maps[i][j]-maps[i][j+1]);
}
}
}
sort(edge+1,edge+numedge+1,cmp);//权值排序
for(i=1;i<=numedge;i++)
{
int x=finds(edge[i].a);
int y=finds(edge[i].b);
if(x!=y)
{
connect(x,y);
ans+=edge[i].num;
}
}
printf("Case #%d:\n%d\n",cas++,ans);
}
return 0;
}