AcWing 1251. 打击犯罪(详细的二分+dfs,看就会)
原题链接
简单
作者:
dsi
,
2025-01-13 14:30:42
,
所有人可见
,
阅读 10
算法(二分 + bfs)
C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1010;
vector<vector<int>> grap;
vector<bool> visited;
int n;
int bfs(int start){
visited[start] = true;
queue<int> q;
q.push(start);
int countSize = 0;
while(!q.empty()){
int index = q.front();
q.pop();
countSize ++;
for (int neighbor : grap[index]){
if (!visited[neighbor]){
visited[neighbor] = true;
q.push(neighbor);
}
}
}
return countSize;
}
bool check(int k){
fill(visited.begin(), visited.end(), false);
for (int i = 1; i <= k; i ++){
visited[i] = true;
}
int maxSize = 0;
for (int i = 1; i <= n; i ++){
if (!visited[i]){
maxSize = max(maxSize, bfs(i));
}
}
return maxSize <= n / 2;
}
int main(){
cin >> n;
grap.resize(n + 1);
visited.resize(n + 1, false);
for (int i = 1; i <= n; i ++){
int a;
cin >> a;
for (int j = 0; j < a; j ++){
int neighbor;
cin >> neighbor;
grap[i].push_back(neighbor);
}
}
int left = 1, right = n, result = n;
while(left <= right){
int mid = (left + right) >> 1;
if (check(mid)){
result = mid;
right = mid - 1;
}else{
left = mid + 1;
}
}
cout << result << endl;
return 0;
}