CCF 201709-4 通信網絡--BFS+vector(鄰接表存儲)

思路:

每個節點用BFS或者DFS正向,反向遍歷兩次,記錄訪問過的節點,若所有節點均訪問過則符合要求,總數加一。

易錯點:

本題數據結構應使用鄰接表存儲;若使用鄰接矩陣存儲則會導致超時。

#include<bits/stdc++.h>
using namespace std;

const int N=1010;
vector<int>adj1[N],adj2[N];

bool inq1[N],inq2[N];

void BFS(int u,vector<int> adj[],bool inq[]){
	int temp=u;
	fill(inq,inq+N+1,false);
	queue<int> q;
	q.push(u);
	inq[u]=true;
	while(!q.empty()){
		int u=q.front();
		q.pop();
		for(int j=0;j<adj[u].size();j++){
			int v=adj[u][j];
			if(inq[v]==false&&adj[u][j]!=0){
				q.push(v);
				inq[v]=true;
			}
		}
	}
}

int main(){
	//輸入 
	int n,m,ans=0;
	cin>>n>>m;
	for(int i=0;i<m;i++){
		int a,b;
		cin>>a>>b;
		adj1[a].push_back(b);
		adj2[b].push_back(a);
	}
	//處理
	for(int i=1;i<n+1;i++){
		int flag=1;
		BFS(i,adj1,inq1),BFS(i,adj2,inq2);
		for(int j=1;j<=n;j++){
			if(inq1[j]==0&&inq2[j]==0){
				flag=0;
				break;
			}
		}
		if(flag==1)ans++;
	} 
	cout<<ans;
	return 0;
}

樣例:

/*
4 4
1 2
1 3
2 4
3 4
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章