int minTreeGra(int root, int n, int m)
{
int ret = 0;
while(true)
{
//找最小入边
for(int i = 0; i < n; i++) in[i] = INF;
for(int i = 0; i < m; i++)
{
int u = edge[i].u;
int v = edge[i].v;
if(edge[i].w < in[v] && u != v) {pre[v] = u; in[v] = edge[i].w;} //去除自环和重边
}
for(int i = 0; i < n; i++)
{
if(i == root) continue;
if(in[i] == INF) return -1; //除了跟以外有点没有入边,则根无法到达它
}
int cnt = 0; //找环
memset(id, -1, sizeof(id));
memset(vis, -1, sizeof(vis));
in[root] = 0;
for(int i = 0; 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)//缩点
{
for(int u = pre[v]; u != v; u = pre[u]) id[u] = cnt;
id[v] = cnt++;
}
}
if(cnt == 0) break; //无环 则break
for(int i = 0; i < n; i++)
if(id[i] == -1) id[i] = cnt++;
//建新图
for(int i = 0; i < m;)
{
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++].w -= in[v];
else edge[i]=edge[--m];
}
n = cnt;
root = id[root];
}
return ret;
}
朱刘算法模板(最小树形图)
最新推荐文章于 2021-02-21 02:54:06 发布