题意:
有向图,求以1为根的最小树形图的边权之和。
解析:
练了下模板。
算法流程哪都有。
代码:
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 110
#define M 11000
#define x first
#define y second
#define eps 1e-6
#define INF 0x7fffffff
using namespace std;
typedef pair<double,double>Pa;
int tot;
struct Edge
{
int u,v;
double val;
Edge(){}
Edge(int _u,int _v,double _val):u(_u),v(_v),val(_val){}
}edge[M];
Pa point[N];
int n,m,u,v;
double get_dis(Pa &a,Pa &b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
namespace Minimal_Tree_Graph
{
#define fr edge[i].u
#define to edge[i].v
#define Val edge[i].val
int id[N],pre[N],vis[N];
double in[N];
double work(int root,int n)
{
double ret=0;
while(true)
{
for(int i=1;i<=n;i++)
in[i]=INF;
for(int i=1;i<=m;i++)
if(in[to]>Val&&fr!=to)
in[to]=Val,pre[to]=fr;
for(int i=1;i<=n;i++)
if(in[i]==INF&&i!=root)return -1;
int cnt_ring=0;
memset(id,-1,sizeof(id));
memset(vis,-1,sizeof(vis));
in[root]=0;
for(int i=1;i<=n;i++)
{
ret+=in[i];
int v=i;
while(vis[v]!=i&&id[v]==-1&&v!=root){vis[v]=i;v=pre[v];}
if(v!=root&&id[v]==-1)
{
cnt_ring++;
for(int u=pre[v];u!=v;u=pre[u])id[u]=cnt_ring;
id[v]=cnt_ring;
}
}
if(!cnt_ring)break;
for(int i=1;i<=n;i++)
if(id[i]==-1)id[i]=++cnt_ring;
for(int i=1;i<=m;i++)
{
int u=edge[i].u;
int v=edge[i].v;
edge[i].u=id[u];
edge[i].v=id[v];
if(id[u]!=id[v])edge[i].val-=in[v];
}
n=cnt_ring;
root=id[root];
}
return ret;
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
scanf("%lf%lf",&point[i].x,&point[i].y);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
double val=get_dis(point[u],point[v]);
if(u==v)edge[i]=Edge(u,v,INF);
else edge[i]=Edge(u,v,val);
}
double ans=Minimal_Tree_Graph::work(1,n);
if(ans==-1)puts("poor snoopy");
else printf("%.2f\n",ans);
}
}