思路:一些已经连好的边添加一条权值为0的路,然后就是上模板了,又SB忘记init()
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 1000
#define LL long long
int cas=1,T;
const int maxm = 11000;
struct Edge
{
int u,v;
int dist;
Edge(){}
Edge(int u,int v,int d):u(u),v(v),dist(d){}
bool operator < (const Edge&rhs)const
{
return dist < rhs.dist;
}
};
int n,m;
Edge edges[maxm];
int pre[maxn];
int Find(int x)
{
return pre[x]==-1?x:pre[x]=Find(pre[x]);
}
void init()
{
m=0;
memset(pre,-1,sizeof(pre));
}
void AddEdge(int u,int v,int dist)
{
edges[m++]=Edge(u,v,dist);
// printf("%d %d %d\n",u,v,dist);
}
int Kruskal()
{
int sum = 0;
int cnt = 0;
sort(edges,edges+m);
for (int i = 0;i<m;i++)
{
int u = edges[i].u;
int v = edges[i].v;
if (Find(u) != Find(v))
{
pre[Find(u)] = Find(v);
sum+=edges[i].dist;
if (++cnt >= n-1)
break;
}
}
return sum;
}
int main()
{
//freopen("in","r",stdin);
scanf("%d",&n);
init();
int c;
for (int i = 0;i<n;i++)
{
for (int j = 0;j<n;j++)
{
scanf("%d",&c);
if (i<j)
AddEdge(i,j,c);
}
}
int k;
scanf("%d",&k);
while (k--)
{
int a,b;
scanf("%d%d",&a,&b);
a--;
b--;
AddEdge(a,b,0);
}
printf("%d\n",Kruskal());
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}