Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ***********************************************************************************
- ************************************BFS********************************************
- #include<bits/stdc++.h>
- using namespace std;
- #define endl "\n"
- #define ll long long
- #define PI acos(-1.0)
- #define test cout<<"\n****\n"
- #define LCM(a,b) ((a/__gcd(a,b))*b)
- #define READ(f) freopen(f, "r", stdin)
- #define WRITE(f) freopen(f, "w", stdout)
- #define precise fixed(cout);cout<<setprecision(20)
- #define fast ios_base :: sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
- const int N = 1000;
- vector <int> graph[N];
- bool visited[N];
- void BFS(int root){
- visited[root] = true;
- queue<int> que;
- que.push(root);
- while (!que.empty()){
- int parent = que.front();
- que.pop();
- for(int i=0;i<graph[parent].size();i++){
- int child = graph[parent][i];
- if(!visited[child]) {
- visited[child] = true;
- que.push(child);
- }
- }
- }
- }
- int main(){
- int numNode,numEdge;
- cin>>numNode>>numEdge;
- for(int i=0;i<numEdge;i++){
- int node,edge;
- cin>>node>>edge;
- graph[node].push_back(edge);
- graph[edge].push_back(node);
- }
- int root;
- cin>>root;
- memset(visited, false,sizeof(visited));
- int count = 0;
- for(int i=1;i<=numNode;i++){
- if(!visited[i]){
- count++;
- BFS(i);
- }
- }
- cout<<count<<endl;
- return 0;
- }
- ***********************************************************************************
- ************************************DFS********************************************
- #include<bits/stdc++.h>
- using namespace std;
- #define endl "\n"
- #define ll long long
- #define PI acos(-1.0)
- #define test cout<<"\n****\n"
- #define LCM(a,b) ((a/__gcd(a,b))*b)
- #define READ(f) freopen(f, "r", stdin)
- #define WRITE(f) freopen(f, "w", stdout)
- #define precise fixed(cout);cout<<setprecision(20)
- #define fast ios_base :: sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
- const int N = 1000;
- vector <int> graph[N];
- bool visited[N];
- void DFS(int root){
- if(visited[root]){
- return;
- }
- visited[root] = true;
- for(int i=0;i<graph[root].size();i++){
- int child = graph[root][i];
- if(!visited[child]){
- DFS(child);
- }
- }
- }
- int main(){
- int numNode,numEdge;
- cin>>numNode>>numEdge;
- for(int i=0;i<numEdge;i++){
- int node,edge;
- cin>>node>>edge;
- graph[node].push_back(edge);
- graph[edge].push_back(node);
- }
- int root;
- cin>>root;
- memset(visited, false,sizeof(visited));
- int count = 0;
- for(int i=1;i<=numNode;i++){
- if(!visited[i]){
- count++;
- DFS(i);
- }
- }
- cout<<count<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement