次小生成树

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;
}
全部评论

相关推荐

joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
10-24 11:10
山西大学 Java
若梦难了:哥们,面试挂是很正常的。我大中厂终面挂,加起来快10次了,继续努力吧。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务