Hdu1232 smooth engineering and query set

Source: Internet
Author: User

This question is very similar to HDU 1213 how many tables and query sets.

Idea: Suppose we still need to build n-1 routes, and each merge will be reduced by 1.

Reference code:

#include<stdio.h>int fa[1000];int find(int u){    return fa[u]==u?u:fa[u]=find(fa[u]);}int main(){    int i,n,m,u,v,x,y;    scanf("%d%d",&n,&m);    while (n)    {        for (i=1;i<=n;i++) fa[i]=i;        for (i=1;i<=m;i++)        {            scanf("%d%d",&u,&v);            x=find(u);y=find(v);            if (x!=y)            {                fa[x]=y;                n--;            }        }        n--;        printf("%d\n",n);       scanf("%d%d",&n,&m);    }   return 0;}

Optimization: first store the number of M groups in arrays, and then only store the root nodes of these nodes.

Initial Value Fa [U [I] = U [I]; Fa [V [I] = V [I];

Reference code:

#include<stdio.h>int fa[1000],u[1000],v[1000];int find(int u){    return fa[u]==u?u:fa[u]=find(fa[u]);}int main(){    int i,n,m,x,y;    scanf("%d%d",&n,&m);    while (n)    {        for (i=1;i<=m;i++)        {            scanf("%d%d",&u[i],&v[i]);            fa[u[i]]=u[i];            fa[v[i]]=v[i];        }        for (i=1;i<=m;i++)        {          x=find(u[i]);y=find(v[i]);            if (x!=y)            {                fa[x]=y;                n--;            }        }        n--;        printf("%d\n",n);       scanf("%d%d",&n,&m);    }   return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.