Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 7518 | Accepted: 2526 |
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!
Source
#include<stdio.h>
#include<string.h>
#define MAXN 1005
#define inf 1000000000
int maxe[MAXN][MAXN],g[MAXN][MAXN];
bool inmst[MAXN][MAXN];
int min(int a,int b)
{
if(a<b) return a;
return b;
}
int used[MAXN],pre[MAXN],d[MAXN];
int prim(int n,int g[][MAXN])
{
int r,minc,res=0;
memset(used,0,sizeof(used));
for(int i=0;i<n;i++) d[i]=inf;
pre[0]=0;
d[0]=0;
for(int k=0;k<n;k++)
{
minc=inf;
for(int i=0;i<n;i++)
if(!used[i]&&d[i]<minc) { minc=d[i]; r=i; }
res+=minc;
inmst[pre[r]][r]=inmst[r][pre[r]]=1;
for(int i=0;i<n;i++)
{
if(!used[i]&&g[r][i]<d[i])
{
d[i]=g[r][i];
pre[i]=r;
}
if(used[i]) maxe[i][r]=maxe[r][i]=minc;
}
used[r]=1;
}
return res;
}
int main()
{
int T,n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
g[i][j]=inf;
maxe[i][j]=inf;
}
memset(inmst,0,sizeof(inmst));
while(m--)
{
int x,y,c;
scanf("%d%d%d",&x,&y,&c);
x--;y--;
g[x][y]=g[y][x]=min(g[x][y],c);//防止重边
}
int mst=prim(n,g);
int mst2=inf;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(!inmst[i][j]&&g[i][j]<inf&&maxe[i][j]<inf)
{
if(mst+g[i][j]-maxe[i][j]<mst2)
mst2=mst+g[i][j]-maxe[i][j];
}
if(mst==mst2) printf("Not Unique!/n");
else printf("%d/n",mst);
}
return 0;
}