signed

QiShunwang

“诚信为本、客户至上”

连接格点(kruskal)

2021/3/21 10:34:05   来源:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1010,M=N*N,K=2*N*N;
int p[M],g[N][N],n,m,cnt;
struct node{
    int a,b,dist;
}edges[K];
int find(int x){
    if(p[x]!=x)return p[x]=find(p[x]);
    return p[x];
}
void get_top(){
    int dx[4]={0,1,0,-1};
    int dy[4]={1,0,-1,0};
    int dw[4]={2,1,2,1};
    for(int z=1;z>=0;z--)
    	for(int i=1;i<=n;i++)
    		for(int j=1;j<=m;j++)
    			for(int u=0;u<4;u++)
        			if(u%2==z){				
			            int a=i+dx[u],b=j+dy[u],w=dw[u];
			            if(a<=0||a>n||b<=0||b>m)continue;
			            int x1=g[i][j],x2=g[a][b];
			            if(x1<x2)
			            edges[cnt++]={x1,x2,w};
			        }
}
int main()
{
    cin>>n>>m;
    int res=0;
    for(int t=1,i=1;i<=n;i++)
    	for(int j=1;j<=m;j++,t++)
    		g[i][j]=t; 
    for(int i=1;i<=n*m;i++)
    	p[i]=i;
    int x1,y1,x2,y2;
    while(cin>>x1>>y1>>x2>>y2){
        int a=g[x1][y1],b=g[x2][y2];
        p[find(a)]=p[find(b)];
    }
    get_top();
    for(int i=0;i<cnt;i++){
        int a=find(edges[i].a),b=find(edges[i].b),w=edges[i].dist;
        if(a!=b){
            p[a]=b;
            res+=w;
        }
    }
    cout<<res<<endl;
    return 0;
}