Luogu P1196 [NOI2002] The Legend of Galactic Heroes

Many people have covered this topic in great detail, so I won't repeat it.

To sum up, this can be regarded as a "side-weighted" union, for which we can record the relationship on the edge of the array separately, and then maintain the relationship while finding and unite.

So in this question, we use a d array to record the number of battleships from the current battleship to the battleship in the front of this column of battleships,

Use a size array (in the program to avoid the keyword replaced by siz) to record how many battleships are followed by the current battleship (update d for the convenience of M operation).

Refer to the code for specific maintenance methods.

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXT = 5e5 + 20;
 4 const int MAXN = 3e4 + 20;
 5 
 6 namespace ufs
 7 {
 8     int fa[MAXN], d[MAXN], siz[MAXN];
 9 
10     void init()
11     {
12         for(int i = 1; i <= MAXN; i++)
13             fa[i] = i, siz[i] = 1;
14     }
15 
16     int get(int x)
17     {
18         if(x == fa[x]) return x;
19         int root = get(fa[x]);
20         d[x] += d[fa[x]];
21         return fa[x] = root;
22     }
23 
24     inline void unite(int x, int y)
25     {
26         x = get(x), y = get(y);
27         fa[x] = y, d[x] = siz[y];
28         siz[y] += siz[x];
29     }
30 }
31 
32 
33 int main()
34 {
35     //freopen("p1196.txt", "r", stdin);
36     int T;
37     cin>>T;
38     using namespace ufs;
39     init();
40 
41     char opt;int i, j;
42     while(T--)
43     {
44         scanf(" %c ", &opt);
45         if(opt == 'M')
46         {
47             scanf("%d%d", &i, &j);
48             unite(i, j);
49         }
50         else
51         {
52             scanf("%d%d", &i, &j);
53             if(get(i) != get(j)) puts("-1");
54             else printf("%d\n", abs(d[i] - d[j]) - 1);
55         }
56     }
57     return 0;
58 }

Note a detail: don't forget that d[ x ] holds the number of warships before x, and d[ y ] holds the number of warships before y, so the number of warships between x and y should be the absolute value of the difference between the two Subtract 1 again.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325057098&siteId=291194637