1013 Battle Over Cities (25 分)(图的遍历or并查集)

 

 

 

 

这题用并查集或者dfs都可以做

 

dfs

#include<bits/stdc++.h>

using namespace std;
const int N=1e3+10;
bool mp[N][N];
int n,m,k;
bool vis[N];
void dfs(int v)
{
    vis[v]=true;
    for(int i=1;i<=n;i++){
        if(mp[v][i]&&!vis[i]){
            dfs(i);
        }
    }
}
int main()
{
    fill(mp[0],mp[0]+N*N,false);
    scanf("%d %d %d",&n,&m,&k);
    for(int i=0;i<m;i++){
        int a,b;
        scanf("%d %d",&a,&b);
        mp[a][b]=mp[b][a]=true;
    }
    while(k--){
        fill(vis,vis+N,false);
        int x;
        scanf("%d",&x);
        vis[x]=true;
        int sum=0;
        for(int i=1;i<=n;i++){

            if(!vis[i]){
                sum++;
                dfs(i);
            }
        }
        printf("%d\n",sum-1);
    }
    return 0;
}

 

并查集

#include<bits/stdc++.h>

using namespace std;

vector<pair<int,int> > edge;
int f[1005];
int n,m;
int findth(int x)
{
    if(x==f[x]) return x;
    return f[x]=findth(f[x]);
}
void join(int x,int y)
{
    int fx,fy;
    fx = findth(x);
    fy = findth(y);
    if (fx != fy)
        f[fx] = fy;
}
void solve(int p)
{
    for (int i = 1 ; i <= n ; i++) f[i] = i;
    for (int i = 0 ; i < edge.size() ; i++){
        if (edge[i].first == p || edge[i].second == p) continue;
        join(edge[i].first,edge[i].second);
    }
    int cnt = 0;
    for (int i = 1 ; i <= n ; i++){
        if (i == p)
            continue;
        if(f[i]==i) cnt++;
    }
    printf("%d\n",cnt-1);
}
int main()
{
    int k;
    scanf("%d %d %d",&n,&m,&k);
    edge.resize(m);
    for (int i = 0 ; i < m ; i++)
    {
        int x,y;
        scanf("%d %d",&x,&y);
        edge[i] = make_pair(x,y);
    }
    for (int i = 1 ; i <= k ; i++)
    {
        int q;
        scanf("%d",&q);
        solve(q);
    }
    return 0;
}

 

posted @ 2018-12-11 20:54  12-num  阅读(885)  评论(0编辑  收藏  举报