Description
Definition 1 (Spanning Tree): Consider a connected, undirected graph G = (V, E). A spanning tree of G is a subgraph of G, say T = (V', E'), with the following properties:
1. V' = V.
2. T is connected and acyclic.
Definition 2 (Minimum Spanning Tree): Consider an edge-weighted, connected, undirected graph G = (V, E). The minimum spanning tree T = (V, E') of G is the spanning tree that has the smallest total cost. The total cost of T means the sum of the weights on all the edges in E'.
Input
Output
Sample Input
2 3 3 1 2 1 2 3 2 3 1 3 4 4 1 2 2 2 3 2 3 4 2 4 1 2
Sample Output
3 Not Unique!
/*16ms,224KB*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int Max_V = 102;
const int Max_E = 4952;
struct EDGE
{
int u, v, w;
bool ischoosed;
} edge[Max_E];
int path[Max_V], V, E, bj[Max_V + 2];
bool cmp(const EDGE&a, const EDGE&b)
{
return a.w < b.w;
}
int search_path(int x)
{
if (x != path[x])
path[x] = search_path(path[x]);
return path[x];
}
int Kruskal(int start)
{
int count = 0, sum = 0, x, y;
for (int i = 1; i <= V; i++)
path[i] = i;
for (int i = start; i < E && count < V - 1; i++)
{
x = search_path(edge[i].u);
y = search_path(edge[i].v);
if (x == y)
continue;
bj[count++] = i;//??????????????????????
path[x] = path[y];//修正
sum += edge[i].w;
}
return count < V - 1 ? 0 : sum;
}
int Seckruskal()
{
int count = 0, sum = 0, x, y;
for (int i = 1; i <= V; i++)
path[i] = i;
for (int i = 0; i < E && count < V - 1; i++)
{
x = search_path(edge[i].u);
y = search_path(edge[i].v);
if (x == y || edge[i].ischoosed == true)//把这条边删掉,看有没有另外的MST
continue;
count++;
path[x] = path[y];
sum += edge[i].w;
}
return count < V - 1 ? 0 : sum;
}
int main()
{
int T, i, temp, minMST;
bool flag;
scanf("%d", &T);
while (T--)
{
memset(bj, 0, sizeof(bj));
memset(path, 0, sizeof(path));
memset(edge, 0, sizeof(edge));
flag = false;
scanf("%d%d", &V, &E);
for (i = 0; i < E; i++)
scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w);
sort(edge, edge + E, cmp);
///////////////////////////////////////////////////////
minMST = Kruskal(0);
for (i = 0; i < V - 1; i++)
{
edge[bj[i]].ischoosed = true;
temp = Seckruskal();
edge[bj[i]].ischoosed = false;
if (temp == minMST && temp)
{
flag = true;
break;
}
}
if (flag)
printf("Not Unique!\n");
else
printf("%d\n", minMST);
}
return 0;
}
381



被折叠的 条评论
为什么被折叠?



