华为OD机试 - 无向图染色(Java 2024 E卷 100分)

题目描述

给定一个无向图,要求用红色和黑色对图中的节点进行染色,确保相邻的两个节点不能同时为红色。求有多少种不同的染色方案。

输入描述

  • 第一行输入两个整数 M(节点数)和 N(边数)。
  • 接下来的 N 行,每行包含两个整数 V1V2,表示图中的一条边。

输出描述

输出一个整数,表示染色方案的个数。

解题思路

这个问题可以看作是一个图的着色问题,每个节点有两种颜色选择(红色或黑色),并且相邻节点不能同时为红色。由于图可能不连通,我们需要对每个连通分量分别计算染色方案,然后将结果相乘。

我们可以使用深度优先搜索(DFS)或广度优先搜索(BFS)来遍历图,并为每个节点尝试两种颜色,同时检查相邻节点的颜色是否冲突。

代码实现

Java
import java.util.*;

public class GraphColoring {
    private static int count = 0;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int M = scanner.nextInt();
        int N = scanner.nextInt();
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < M; i++) {
            graph.add(new ArrayList<>());
        }
        for (int i = 0; i < N; i++) {
            int V1 = scanner.nextInt();
            int V2 = scanner.nextInt();
            graph.get(V1).add(V2);
            graph.get(V2).add(V1);
        }
        int[] colors = new int[M];
        Arrays.fill(colors, -1);
        int result = 1;
        for (int i = 0; i < M; i++) {
            if (colors[i] == -1) {
                count = 0;
                dfs(graph, colors, i, 0);
                result *= count;
            }
        }
        System.out.println(result);
    }

    private static void dfs(List<List<Integer>> graph, int[] colors, int node, int color) {
        colors[node] = color;
        if (color == 0) {
            count++;
        }
        for (int neighbor : graph.get(node)) {
            if (colors[neighbor] == -1) {
                dfs(graph, colors, neighbor, 1 - color);
            }
        }
    }
}
Python
def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    M = int(data[0])
    N = int(data[1])
    graph = [[] for _ in range(M)]
    index = 2
    for _ in range(N):
        V1 = int(data[index])
        V2 = int(data[index + 1])
        graph[V1].append(V2)
        graph[V2].append(V1)
        index += 2
    colors = [-1] * M
    result = 1

    def dfs(node, color):
        nonlocal count
        colors[node] = color
        if color == 0:
            count += 1
        for neighbor in graph[node]:
            if colors[neighbor] == -1:
                dfs(neighbor, 1 - color)

    for i in range(M):
        if colors[i] == -1:
            count = 0
            dfs(i, 0)
            result *= count
    print(result)

if __name__ == "__main__":
    main()
C++
#include <iostream>
#include <vector>
using namespace std;

int count = 0;

void dfs(vector<vector<int>>& graph, vector<int>& colors, int node, int color) {
    colors[node] = color;
    if (color == 0) {
        count++;
    }
    for (int neighbor : graph[node]) {
        if (colors[neighbor] == -1) {
            dfs(graph, colors, neighbor, 1 - color);
        }
    }
}

int main() {
    int M, N;
    cin >> M >> N;
    vector<vector<int>> graph(M);
    for (int i = 0; i < N; i++) {
        int V1, V2;
        cin >> V1 >> V2;
        graph[V1].push_back(V2);
        graph[V2].push_back(V1);
    }
    vector<int> colors(M, -1);
    int result = 1;
    for (int i = 0; i < M; i++) {
        if (colors[i] == -1) {
            count = 0;
            dfs(graph, colors, i, 0);
            result *= count;
        }
    }
    cout << result << endl;
    return 0;
}
JavaScript
function main() {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    let M, N;
    let graph = [];
    let colors = [];
    let result = 1;

    rl.on('line', (line) => {
        if (!M) {
            [M, N] = line.split(' ').map(Number);
            graph = new Array(M).fill().map(() => []);
            colors = new Array(M).fill(-1);
        } else {
            const [V1, V2] = line.split(' ').map(Number);
            graph[V1].push(V2);
            graph[V2].push(V1);
            if (--N === 0) {
                for (let i = 0; i < M; i++) {
                    if (colors[i] === -1) {
                        let count = 0;
                        dfs(i, 0);
                        result *= count;
                    }
                }
                console.log(result);
                rl.close();
            }
        }
    });

    function dfs(node, color) {
        colors[node] = color;
        if (color === 0) {
            count++;
        }
        for (const neighbor of graph[node]) {
            if (colors[neighbor] === -1) {
                dfs(neighbor, 1 - color);
            }
        }
    }
}

main();

总结

这个问题可以通过深度优先搜索(DFS)来解决,遍历图中的每个节点,并尝试为其着色。由于图可能不连通,我们需要对每个连通分量分别计算染色方案,并将结果相乘。上述代码提供了Java、Python、C++和JavaScript的实现,可以根据需要选择合适的语言进行使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝白咖啡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值