目录
模拟法:6253.回环句
排序后模拟:6254. 划分技能点相等的团队
BFS:6255. 两个城市间路径的最小分数
BFS:6256. 将节点分成尽可能多的组
模拟法:6253.回环句
这道题直接按照题目的意思暴力模拟即可:
class Solution {
public:
bool isCircularSentence(string sentence) {
if (sentence[0] != sentence[sentence.size() - 1]) {
return false;
}
for (int i = 0; i < sentence.size(); i++) {
if (sentence[i] == ' ') {
if (sentence[i - 1] != sentence[i + 1]) {
return false;
}
}
}
return true;
}
};
排序后模拟:6254. 划分技能点相等的团队
先排序后,判断第i个和第n-i个加起来的和是否相等,如果不相等,直接返回-1结束。然后把这些加和,返回结果即可。
class Solution {
public:
long long dividePlayers(vector<int>& skill) {
sort(skill.begin(), skill.end());
long long ans = 0;
long long temp = skill[0] + skill[skill.size() - 1];
for (int i = 0; i < skill.size() / 2; i++) {
if (skill[i] + skill[skill.size() - i - 1] != temp) {
return -1;
} else {
ans += skill[i] * skill[skill.size() - i - 1];
}
}
return ans;
}
};
BFS:6255. 两个城市间路径的最小分数
class Solution {
public:
int minScore(int n, vector<vector<int>>& roads) {
vector<vector<pair<int, int>>> arr(n);
for (const auto& r : roads) {
int u = r[0] - 1, v = r[1] - 1, d = r[2];
arr[u].emplace_back(v, d);
arr[v].emplace_back(u, d);
}
int ret = INT_MAX;
vector<int> visit(n);
queue<int> q;
q.push(0);
while (!q.empty()) {
int f = q.front();
q.pop();
if (visit[f] != 0) {
continue;
}
visit[f] = 1;
for (auto [next, d] : arr[f]) {
q.push(next);
ret = min(ret, d);
}
}
return ret;
}
};
BFS:6256. 将节点分成尽可能多的组
贴一个大佬的回答吧:
class Solution {
public:
int magnificentSets(int n, vector<vector<int>> &edges) {
vector<vector<int>> g(n);
for (auto &e : edges) {
int x = e[0] - 1, y = e[1] - 1;
g[x].push_back(y);
g[y].push_back(x);
}
int time[n], clock = 0; // time 充当 vis 数组的作用(避免在 BFS 内部重复创建 vis 数组)
memset(time, 0, sizeof(time));
auto bfs = [&](int start) -> int { // 返回从 start 出发的最大深度
int depth = 0;
time[start] = ++clock;
vector<int> q = {start};
while (!q.empty()) {
vector<int> nxt;
for (int x : q)
for (int y : g[x])
if (time[y] != clock) { // 没有在同一次 BFS 中访问过
time[y] = clock;
nxt.push_back(y);
}
q = move(nxt);
++depth;
}
return depth;
};
int8_t color[n]; memset(color, 0, sizeof(color));
vector<int> nodes;
function<bool(int, int8_t)> is_bipartite = [&](int x, int8_t c) -> bool { // 二分图判定,原理见视频讲解
nodes.push_back(x);
color[x] = c;
for (int y : g[x])
if (color[y] == c || color[y] == 0 && !is_bipartite(y, -c))
return false;
return true;
};
int ans = 0;
for (int i = 0; i < n; ++i) {
if (color[i]) continue;
nodes.clear();
if (!is_bipartite(i, 1)) return -1; // 如果不是二分图(有奇环),则无法分组
// 否则一定可以分组
int max_depth = 0;
for (int x : nodes) // 枚举连通块的每个点,作为起点 BFS,求最大深度
max_depth = max(max_depth, bfs(x));
ans += max_depth;
}
return ans;
}
};
https://leetcode.cn/problems/divide-nodes-into-the-maximum-number-of-groups/solution/mei-ju-qi-dian-pao-bfs-by-endlesscheng-s5bu/