zoukankan      html  css  js  c++  java
  • 大招秒杀

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 typedef struct ufset *UFset;
     4 struct ufset
     5 {
     6     int parent[100001];
     7     int root[100001];
     8 }UFS;
     9 int UFfind(int e,UFset U)
    10 {
    11     int i,j=e;
    12     while(U->root[j]==0)
    13     {
    14         //printf("parent[%d]=%d root=%d
    ",j,U->parent[j],U->root[j]);
    15         j=U->parent[j];
    16     }
    17     while(j!=e)
    18     {
    19         i=U->parent[e];
    20         U->parent[e]=j;
    21         e=i;
    22     }
    23     return j;
    24 }
    25 int UFunion(int i,int j,UFset U)
    26 {
    27     if(U->parent[i]<U->parent[j])
    28     {
    29         U->parent[j]+=U->parent[i];
    30         U->root[i]=0;
    31         U->parent[i]=j;
    32         return j;
    33     }
    34     else
    35     {
    36         U->parent[i]+=U->parent[j];
    37         U->root[j]=0;
    38         U->parent[j]=i;
    39         return i;
    40     }
    41 }
    42 int main()
    43 {
    44     UFset UF;
    45     UF=(UFset)malloc(sizeof(UFS));
    46     int e,n,m,k,x,i,a,b,t1,t2;
    47     scanf("%d %d %d",&n,&m,&k);
    48     for(e=1;e<=n+1;e++)
    49     {
    50         UF->parent[e]=1;
    51         UF->root[e]=1;
    52     }
    53     for(i=0;i<m;i++)
    54     {
    55         scanf("%d %d",&a,&b);
    56         t1=UFfind(a,UF);t2=UFfind(b,UF);
    57         if(t1!=t2)
    58         {
    59             UFunion(t1,t2,UF);
    60         }
    61     }
    62     for(i=0;i<k;i++)
    63     {
    64         scanf("%d",&x);
    65         printf("%d
    ",UF->parent[UFfind(x,UF)]);
    66     }
    67     return 0;
    68 }
    View Code

    并查集简单又好用

  • 相关阅读:
    python闯关_Day012
    python闯关_Day010
    python闯关_Day009
    python闯关_Day008
    python闯关_Day07
    什么是PRD、MRD与BRD?
    Python中logging日志使用
    git一些常用的命令
    Python第三方库
    FastDFS分布式存储服务器安装
  • 原文地址:https://www.cnblogs.com/zeze/p/UFS.html
Copyright © 2011-2022 走看看