HDOJ 1301最小生成树的Kruskal算法

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1301

将结点的字符信息处理成点信息即可,代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned int ui;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 #define pf printf
 7 #define mem(a,b) memset(a,b,sizeof(a))
 8 #define prime1 1e9+7
 9 #define prime2 1e9+9
10 #define pi 3.14159265
11 #define lson l,mid,rt<<1
12 #define rson mid+1,r,rt<<1|1
13 #define scand(x) scanf("%llf",&x) 
14 #define f(i,a,b) for(int i=a;i<=b;i++)
15 #define scan(a) scanf("%d",&a)
16 #define mp(a,b) make_pair((a),(b))
17 #define P pair<int,int>
18 #define dbg(args) cout<<#args<<":"<<args<<endl;
19 #define inf 0x3f3f3f3f
20 const int maxn=1e6+10;
21 int n,m,t;
22 inline int read(){
23     int ans=0,w=1;
24     char ch=getchar();
25     while(!isdigit(ch)){if(ch=='-')w=-1;ch=getchar();}
26     while(isdigit(ch))ans=(ans<<3)+(ans<<1)+ch-'0',ch=getchar();
27     return ans*w;
28 }
29 struct node{
30     int u,v,w;
31 }e[maxn];
32 int cnt=0,ans;
33 int f[maxn];
34 void init()
35 {
36     f(i,1,n)f[i]=i;
37     cnt=0;
38     ans=0;
39 }
40 bool cmp(node& a,node& b)
41 {
42     return a.w<b.w;
43 }
44 int find(int x)
45 {
46     return x==f[x]?x:f[x]=find(f[x]);
47 }
48 void Union(int x,int y,int w)
49 {
50     int fx=find(x);
51     int fy=find(y);
52     if(fx==fy)return;
53     else 
54     {
55         f[fx]=fy;
56         ans+=w;
57     }
58 }
59 int main()
60 {
61     //freopen("input.txt","r",stdin);
62     //freopen("output.txt","w",stdout);
63     std::ios::sync_with_stdio(false);
64     while(scan(n))
65     {
66         if(!n)break;
67         init();
68         char s[5];
69         f(i,1,n-1)
70         {
71             scanf(" %s",s);
72             int tmp1=s[0]-'A'+1;
73             m=read();
74             while(m--)
75             {
76                 scanf("%s",s);
77                 t=read();
78                 int tmp2=s[0]-'A'+1;
79                 e[++cnt].u=tmp1;
80                 e[cnt].v=tmp2;
81                 e[cnt].w=t;
82             }
83         }
84         sort(e+1,e+cnt+1,cmp);
85         f(i,1,cnt)Union(e[i].u,e[i].v,e[i].w);
86         pf("%d\n",ans);
87     }
88 } 

 

上一篇:hdu 1573扩展欧几里得算法求一元线性同余方程


下一篇:hdu1908 逆序对