• 牛客训练联盟热身训练赛第二场补题报告


    F.Interstellar Love

    1.思路

       并查集求无向图连通分量和闭环数:连通分量用判断祖先节点是否等于自身节点求出,两个节点的祖先节点相同且又添加了新边,则闭环数++。

    2.代码

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 #define ll long long
     4 int fa[10005];
     5 int vis[10005];
     6 int sig[10005];
     7 int find(int x) {
     8     if(fa[x] == x) {
     9         return x;
    10     } else {
    11         return fa[x] = find(fa[x]);
    12     }
    13 }
    14 void merge(int x, int y) {
    15     int fx = find(x);
    16     int fy = find(y);
    17     if(fx != fy) {
    18         fa[fx] = fy;
    19         if(sig[fx]) {
    20             sig[fy] = 1;
    21         }
    22     } else {
    23         sig[fx] = 1;
    24     }
    25 }
    26 int main() {
    27     int t;
    28     cin >> t;
    29     for(int i = 1; i <= t; i++) {
    30         int n, m;
    31         cin >> n >> m;
    32         for(int j = 0; j <= n; j++) {
    33             fa[j] = j;
    34             vis[j] = 0;
    35             sig[j] = 0;
    36         }
    37         int x, y;
    38         for(int j = 0; j < m; j++) {
    39             cin >> x >> y;
    40             vis[x] = 1;
    41             vis[y] = 1;
    42             merge(x, y); 
    43         }
    44         int cnt = 0;
    45         int huan = 0;
    46         for(int j = 1; j <= n; j++) {
    47             if(j == fa[j] && vis[j]) {
    48                 cnt++;
    49                 if(sig[j] == 1) {
    50                     huan++;
    51                 }
    52             }
    53         }
    54         printf("Night sky #%d: %d constellations, of which %d need to be fixed.\n\n", i, cnt, huan);
    55     }
    56 
    57     return 0;
    58 }
    View Code
  • 相关阅读:
    python
    python
    python
    python
    python
    python
    python
    python
    [ThinkPHP] 从一个表中获得栏目对应的ID,从另一个表获得属于这些栏目的文章
    [thinkPHP] buildSql可以查看tp CURD操作对应的SQL
  • 原文地址:https://www.cnblogs.com/lvguapi/p/14558614.html
Copyright © 2020-2023  润新知