Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

hdu 2120 Ice_cream's world I http://acm.hdu.edu.cn/showproblem.php?pid=2120    2012-12-22

并查集算环的个数

View Code
 1 #include <cstdio>
 2 using namespace std;
 3 
 4 const int N=1010;
 5 int fa[N];
 6 int find(int x)
 7 {
 8     return x==fa[x]?x:fa[x]=find(fa[x]);
 9 }
10 int main()
11 {
12     int n,m;
13     while(~scanf("%d%d",&n,&m))
14     {
15         for(int i=0;i<n;i++) fa[i]=i;
16         int ans=0;
17         for(int i=0;i<m;i++)
18         {
19             int u,v;
20             scanf("%d%d",&u,&v);
21             int fu=find(u);
22             int fv=find(v);
23             if(fu==fv) ans++;
24             else fa[fu]=fv;
25         }
26         printf("%d\n",ans);
27     }
28     return 0;
29 }

 

hdu 3938 Portal http://acm.hdu.edu.cn/showproblem.php?pid=3938

离线,一个无向图,A B之间的路径长度为所有A到B的路径最长边的最小值,多次询问小于L的路径数

View Code
 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 const int N=10010,M=50010;
 6 struct edge
 7 {
 8     int u,v,w;
 9     bool operator < (const edge &e)const
10     {
11         return w<e.w;
12     }
13     void input()
14     {
15         scanf("%d%d%d",&u,&v,&w);
16     }
17 }e[M];
18 struct que
19 {
20     int ask,ans,idx;
21     bool operator < (const que &q)const
22     {
23         return ask<q.ask;
24     }
25     void input(int i)
26     {
27         scanf("%d",&ask);
28         ans=0;
29         idx=i;
30     }
31 }q[N];
32 bool cmp(const que &a,const que &b)
33 {
34     return a.idx<b.idx;
35 }
36 
37 int pa[N],sum[N];
38 int find(int x)
39 {
40     return pa[x]==x?x:pa[x]=find(pa[x]);
41 }
42 int main()
43 {
44     int n,m,Q;
45     while(~scanf("%d%d%d",&n,&m,&Q))
46     {
47         for(int i=1;i<=n;i++) {pa[i]=i; sum[i]=1;}
48         for(int i=0;i<m;i++) e[i].input();
49         sort(e,e+m);
50         for(int i=0;i<Q;i++) q[i].input(i);
51         sort(q,q+Q);
52         for(int i=0,k=0;i<Q;i++)
53         {
54             if(i>0) q[i].ans=q[i-1].ans;
55             int l=q[i].ask;
56             while(k<m && e[k].w<=l)
57             {
58                 int fu=find(e[k].u);
59                 int fv=find(e[k].v);
60                 if(fu!=fv)
61                 {
62                     q[i].ans+=sum[fu]*sum[fv];
63                     sum[fu]+=sum[fv];
64                     pa[fv]=fu;
65                 }
66                 k++;
67             }
68         }
69         sort(q,q+Q,cmp);
70         for(int i=0;i<Q;i++) printf("%d\n",q[i].ans);
71     }
72     return 0;
73 }

 

posted on 2012-11-24 11:50  Qiuqiqiu  阅读(111)  评论(0编辑  收藏  举报