牛客小白月赛25 C.白魔法师

主要思路: 

BFS求一下每个白色连通快的大小,然后对每一个黑色点逐个判断,判断通过这个黑色点可以连通多少个白色连通块,把这些白色连通块大小相加再+1,最后答案维护一下最大值就行了。

如果没有黑色点的话,直接输出最大的白色连通块就好。否则输出上述维护的ans。

这个题真滴就差一点,一开始犯浑想成求树上最大直径了,想成只能连接两个连通块,fo自己了,也算是个有点小难度的图论题吧。

看着题解很多都是并查集做的,本蒟蒻的比标程还稍微快那么一倍,O(∩_∩)O哈哈~

#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;
}

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/106203788
今日推荐