本旨:
BFSは、高速で接続された各白のサイズを見つけて、各黒点を1つずつ判断し、この黒点を介して接続できる白接続ブロックの数を判断し、これらの白接続ブロックのサイズを+1に加算すると、最終的に答えが最大として維持されます。価値はあります。
黒点がない場合は、最大の白接続ブロックを直接出力してください。それ以外の場合は、上記で維持されているansを出力します。
この質問はほぼ真実です。最初は、ツリー上で最大の直径だと思いました。接続された2つのブロックしか接続できないと思い、少し難しいグラフトピックでした。
問題の解決策の多くが複合検索で行われていることを考えると、Ben Konjacは、標準のプロセスであるO(∩_∩)Ohaha〜よりもわずかに高速です。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO \
ios::sync_with_stdio(false); \
// cin.tie(0); \
// cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 2e5 + 10;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
char color[maxn];
int size[maxn];
int ID[maxn];
bool vis[maxn];
int n, k; // k 作为标号
int maxsize = 0;
vector<int> v[maxn];
void BFS(int s)
{
queue<int> q;
q.push(s);
vis[s] = 1;
ID[s] = k;
int cnt = 1;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = 0; i < v[u].size(); i++)
{
int vv = v[u][i];
if (!vis[vv] && color[vv] == 'W')
{
ID[vv] = k;
cnt++;
vis[vv] = 1;
q.push(vv);
}
}
}
size[k] = cnt;
maxsize = max(maxsize, cnt);
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
int c = 0; // 记录黑色个数
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf(" %c", &color[i]);
if (color[i] == 'B')
++c;
}
int x, y;
for (int i = 1; i <= n - 1; i++)
{
scanf("%d %d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
}
for (int i = 1; i <= n; i++)
if (color[i] == 'W' && !vis[i])
{
++k;
BFS(i);
}
int ans = 0;
for (int i = 1; i <= n; i++)
{
int t = 0;
if (color[i] == 'B')
{
for (int j = 0; j < v[i].size(); j++)
{
if (color[v[i][j]] == 'W')
t += size[ID[v[i][j]]];
}
}
ans = max(ans, t);
}
if (c == 0)
{
cout << maxsize;
}
else
{
cout << ans + 1;
}
return 0;
}