1013 Battle Over Cities

Cpp 并查集

#include 
using namespace std;
int n, m, k;
const int MAX = 1002;
int G[MAX][MAX];
int parent[MAX];

// 获得根节点
int get_root(int parent[], int p)
{
    while (p != parent[p])
    {
        parent[p] = parent[parent[p]];
        p = parent[p];
    }
    return p;
}

// 判断两节点是否连通
bool connect(int parent[], int p, int q)
{
    return get_root(parent, p) == get_root(parent, q);
}

// 连接两个点
bool union_v(int parent[], int w[], int p, int q)
{
    int p_root = get_root(parent, p);
    int q_root = get_root(parent, q);
    if (p_root != q_root)
    {
        if (w[p_root] > w[q_root])
        {
            parent[p_root] = q_root;
        }
        else if (w[p_root] < w[q_root])
        {
            parent[p_root] = q_root;
        }
        else
        {
            parent[q_root] = p_root;
            w[p_root]++;
        }
        return true;
    }
    return false;
}

int get_repair_num(int G[MAX][MAX], int lost)
{
    int g[MAX][MAX];
    // 连通分量的权重
    int w[MAX];

    // 数组拷贝
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            g[i][j] = G[i][j];
        }
    }

    // 封锁lost节点
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (j == lost || i == lost)
            {
                g[i][j] = 0;
            }
        }
    }

    for (int i = 1; i <= n; i++)
    {
        parent[i] = i;
        w[i] = 0;
    }

    int res = n;
    // 生成连通分量
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (g[i][j] == 1 && union_v(parent, w, i, j) == true)
            {
                res--;
            }
        }
    }

    return res - 2;
}

int main()
{
    // 关闭同步,否则最后一个点会超时
    ios_base::sync_with_stdio(false);

    // 读取数据,邻接矩阵存储
    cin >> n >> m >> k;
    int c1, c2;
    for (int i = 1; i <= m; i++)
    {
        cin >> c1 >> c2;
        G[c1][c2] = 1;
        G[c2][c1] = 1;
    }

    // 模拟输出
    int lost, ans = 0;
    for (int i = 0; i < k; i++)
    {
        cin >> lost;
        ans = get_repair_num(G, lost);
        cout << ans << endl;
    }

    return 0;
}

你可能感兴趣的:(1013 Battle Over Cities)