文章

6

粉丝

375

获赞

3

访问

46.7k

头像
DFS
P1456 上海交通大学机试题
发布于2021年3月18日 09:41
阅读数 7.8k

#include <bits/stdc++.h>
using namespace std;
vector<int>g[1010];
bool vis[1010];
void dfs(int x){
    vis[x]=true;
    for(int y:g[x]){
        if(!vis[y]){
            dfs(y);
        }
    }
}
int main(){
    unordered_set<int>st;
    int x,y;
    while(cin>>x>>y){
        st.insert(x);
        st.insert(y);
        g[x].push_back(y);
        g[y].push_back(x);
    }
    int ans=0;
    for(int x:st){
        if(!vis[x]){
            ans++;
            dfs(x);
        }
    }
    cout<<ans;
    return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发