题解:AT_abc261_h [ABC261Ex] Game on Graph
CuteNails
·
·
题解
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
#include <utility>
using namespace std;
// 使用别名简化类型定义
using ll = long long;
using Pair = pair<int, int>;
// 定义最大节点数和无穷大值
const int Maxn = 2e5;
const ll inf = 1e18;
// 自定义的读取函数,用于从标准输入读取整数
int read() {
int num = 0; // 用于存储读取的整数
char ch; // 用于存储读取的字符
bool negative = false; // 用于标记是否为负数
// 跳过非数字字符,若遇到负号则标记为负数
while ((ch = getchar()) && (ch < '0' || ch > '9')) {
if (ch == '-') negative = true;
}
// 读取数字部分
num = ch - '0';
while ((ch = getchar()) && (ch >= '0' && ch <= '9')) {
num = num * 10 + (ch - '0');
}
// 根据是否为负数返回结果
return negative? -num : num;
}
// 图的邻接表表示,v 存储正向边,w 存储反向边
vector<vector<Pair>> v(Maxn + 5);
vector<vector<Pair>> w(Maxn + 5);
// oud 数组记录每个节点的出度,oud[x][0] 和 oud[x][1] 分别表示两种情况的出度
int oud[Maxn + 5][2];
// vis 数组记录节点是否被访问过,vis[x][0] 和 vis[x][1] 分别表示两种情况的访问状态
bool vis[Maxn + 5][2];
// f 数组存储从初始节点到其他节点的最短或最长路径值,f[x][0] 和 f[x][1] 分别表示两种情况的值
ll f[Maxn + 5][2];
// 定义优先队列节点结构
struct Node {
int x; // 节点编号
int y; // 表示某种情况(0 或 1)
ll z; // 从初始节点到该节点的路径值
// 重载小于运算符,用于优先队列的排序,按照路径值从大到小排序
bool operator<(const Node& other) const {
return z > other.z;
}
};
// 广度优先搜索函数,用于计算从初始节点到其他节点的最短或最长路径
void bfs() {
priority_queue<Node> pq; // 定义优先队列
// 将所有出度为 0 的节点作为初始节点加入队列
for (int i = 1; i <= Maxn; ++i) {
if (!oud[i][0]) {
pq.push({i, 0, 0}); // 将节点 i 的情况 0 加入队列,路径值为 0
pq.push({i, 1, 0}); // 将节点 i 的情况 1 加入队列,路径值为 0
f[i][0] = 0; // 初始化节点 i 的情况 0 的路径值为 0
f[i][1] = 0; // 初始化节点 i 的情况 1 的路径值为 0
}
}
// 优先队列不为空时,进行循环
while (!pq.empty()) {
Node k = pq.top(); // 取出队首节点
pq.pop(); // 弹出队首节点
int x = k.x; // 取出节点编号
int t = k.y; // 取出情况编号
// 如果该节点已经被访问过,则跳过
if (vis[x][t]) continue;
vis[x][t] = true; // 标记该节点为已访问
// 遍历该节点的所有反向边
for (const auto& i : w[x]) {
int y = i.first; // 取出边的终点节点编号
int z = i.second; // 取出边的权值
// 减少终点节点的对应出度
oud[y][t ^ 1]--;
// 根据当前情况更新终点节点的路径值
if (t == 1) {
f[y][0] = min(f[y][0], f[x][1] + z);
} else {
f[y][1] = max(f[y][1], f[x][0] + z);
}
// 如果终点节点的对应出度为 0,则将其加入队列
if (!oud[y][t ^ 1]) {
pq.push({y, t ^ 1, f[y][t ^ 1]});
} else if (t == 1) {
pq.push({y, 0, f[y][0]});
}
}
}
}
int main() {
int n = read(); // 读取节点数
int m = read(); // 读取边数
int s = read(); // 读取目标节点编号
// 读取每条边的信息,并更新图的邻接表和出度数组
for (int i = 0; i < m; ++i) {
int a = read(); // 读取边的起点节点编号
int b = read(); // 读取边的终点节点编号
int c = read(); // 读取边的权值
v[a].push_back({b, c}); // 将正向边加入邻接表
w[b].push_back({a, c}); // 将反向边加入邻接表
oud[a][0]++; // 增加起点节点的情况 0 的出度
oud[a][1]++; // 增加起点节点的情况 1 的出度
}
// 初始化所有节点的情况 0 的路径值为无穷大
for (int i = 1; i <= n; ++i) {
f[i][0] = inf;
}
// 执行广度优先搜索
bfs();
// 根据目标节点的访问状态输出结果
if (!vis[s][0]) {
cout << "INFINITY\n"; // 如果目标节点的情况 0 未被访问过,输出 INFINITY
} else {
cout << f[s][0] << "\n"; // 否则输出目标节点的情况 0 的路径值
}
return 0;
}