次小生成树

The Unique MST POJ - 1679


const int LEN = 100000;//有多少条边
const int LEN2 = 110;//有多少个点
int N,M;
struct Node
{

    int x;
    int y;
    int weight;

};
Node node[LEN];
bool operator <(const Node &a,const Node &b)
{
    return a.weight < b.weight;
}
bool cmp(const Node &a,const Node &b)
{
    return a.weight  < b.weight;
}
int sign1[LEN];
int Max_edge[LEN2][LEN2];//最小生成树从i到j最权值最大边的权值
int Matrix[LEN2][LEN2];
bool  sign[LEN2][LEN2];

int F[LEN2];
int vis[LEN2];
void Init(void)
{
    me(sign1);
    for(int i = 0; i <= N; ++i)
        F[i] = i;
    me(sign);
    me(vis);
}
int Find(int x)
{
    return x == F[x]?x:F[x] = Find(F[x]);
}
void Dfs(int x)
{
    for(int i =1; i <= N; ++i)
    {
        if(sign[x][i]&&!vis[i])
        {

            Max_edge[x][i] = Max_edge[i][x] = Matrix[x][i];
            for(int j = 1; j <= N; ++j)
            {
                if(vis[j]&&j!=x)
                {

                    Max_edge[i][j] = Max_edge[j][i] = max(Max_edge[j][x],Max_edge[x][i]);
                }

            }
            vis[i] = 1;
            Dfs(i);
        }
    }
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>N>>M;
        if(M>0)
        {
            Init();
            for(int i = 0; i < M; ++i)
            {
                scanf("%d %d %d",&node[i].x,&node[i].y,&node[i].weight);

                Matrix[node[i].x][node[i].y] = Matrix[node[i].y][node[i].x] = node[i].weight;
            }
            sort(node,node+M);
            int All_cost = 0;
            for(int i = 0; i < M; ++i)
            {
                int x = Find(node[i].x);
                int y = Find(node[i].y);
                if(x!=y)
                {
                    sign[node[i].x][node[i].y] = sign[node[i].y][node[i].x] = 1;

                    F[x] = y;
                    sign1[i] = 1;
                    All_cost += node[i].weight;
                }
            }


            vis[1] = 1;

            Dfs(1);
            int flag = 0;
            for(int i = 0; i < M; ++i)
            {
                if(!sign1[i]&&node[i].x!=node[i].y)
                {
                    if(Max_edge[node[i].x][node[i].y] >= node[i].weight)
                    {
                        flag = 1;
                        break;
                    }
                }
            }
            if(flag)
                printf("Not Unique!\n");
            else
                printf("%d\n",All_cost);


        }
        else
            cout<<0<<endl;
    }



    return 0;
}

posted on 2017-08-22 01:01  zzuzxy  阅读(112)  评论(0编辑  收藏  举报

导航