PAT Advanced 1013

Battle Over Cities

简单的并查集应用:

思路

先假设这个点不在图里面,然后构建并查集,算有几个连通分量,算完之后,连通分量数-1就能得到需要修建多少条路。

源码

#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int tree[1010];
//ifstream fin("fin.txt");
//streambuf *old = cin.rdbuf(fin.rdbuf());
int N, M, K;
int ans[1010];
struct node
{
    int f, r;
};
node edge[1010*1010];
void init()
{
    for (int i = 1; i <= N; i++)
    {
        tree[i] = i;
        ans[i] = 0;
    }
}
int findroot(int x)
{
    int r = x;
    while (tree[r] != r)
        r = tree[r];
    int i = x, j;
    while (i != r)
    {
        j = tree[i];
        tree[i] = r;
        i = j;
    }
    return r;
}

void merge(int a, int b)
{
    int fx = findroot(a), fy = findroot(b);
    if (fx != fy)
    {
        tree[fy] = fx;
    }
}
void solve()
{
    int city;
    int highway=0;
    for (int i = 1; i <= K; i++)
    {
        cin >> city;
        init();
        for (int j = 1; j <= M; j++)
        {
            if (edge[j].f != city &&edge[j].r != city)
            {
                merge(edge[j].f, edge[j].r);
            }
        }
        for (int j = 1; j <= N; j++)
        {
            if (j != city)
                findroot(j);
        }
        for (int j = 1; j <= N; j++)
        {
            if (tree[j]==j&&j!=city)
            {
                highway++;
            }
        }
        if (!highway)
            cout << 0 << endl;
        else
            cout << highway - 1 << endl;
        highway = 0;
    }
}
void input()
{
    cin >> N >> M >> K;
    int c1, c2;
    init();
    for (int i = 1; i <= M; i++)
    {
        cin >> c1 >> c2;
        edge[i].f = c1;
        edge[i].r = c2;
    }
    if (N)
        solve();
    else
        cout << 0 << endl;

}
int main()
{
    input();
    return 0;
}

目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值