L2-023 图着色问题(Java)

题目链接:PTA | 程序设计类实验辅助教学平台

图着色问题是一个著名的NP完全问题。给定无向图G=(V,E),问可否用K种颜色为V中的每一个顶点分配一种颜色,使得不会有两个相邻顶点具有同一种颜色?

但本题并不是要你解决这个着色问题,而是对给定的一种颜色分配,请你判断这是否是图着色问题的一个解。

输入格式:

输入在第一行给出3个整数V(0

输出格式:

对每种颜色分配方案,如果是图着色问题的一个解则输出Yes,否则输出No,每句占一行。

输入样例:

6 8 3
2 1
1 3
4 6
2 5
2 4
5 4
5 6
3 6
4
1 2 3 3 1 2
4 5 6 6 4 5
1 2 3 4 5 6
2 3 4 2 3 4

输出样例:

Yes
Yes
No
No

题目分析 :

    这道题只需要把每条边存储起来,根据颜色判断每条边是否有相同的
    Java必须使用快读,否则分拿不全。

Java题解:

import java.io.*;
import java.util.*;

public class Main {
   static Node[] node;
    static StreamTokenizer in;
    static PrintWriter out;

    //定义相连的边
    static class Node {
        int x;
        int y;

        public Node(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    public static void main(String[] args) throws IOException {
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(new OutputStreamWriter(System.out));
        int v = nextInt();
        int e = nextInt();
        int k = nextInt();
        node = new Node[e];

        for (int i = 0; i < e; i++) {
            int x = nextInt();
            int y = nextInt();
            node[i] = new Node(x, y);
        }
        int n = nextInt();
        HashSet set = new HashSet<>();
        while (n-- > 0) {
            int[] arr = new int[v + 1];
            set.clear();
            for (int i = 1; i <= v; i++) {
                arr[i] = nextInt();
                set.add(arr[i]);
            }
            if (set.size() != k) {
                out.println("No");
            } else {
                out.println(solve(arr) ? "Yes" : "No");
            }
        }
        out.close();
    }

    public static int nextInt() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }

    public static boolean solve(int[] arr) {
        for (Node value : node) {
            if (arr[value.x] == arr[value.y]) {
                return false;
            }
        }
        return true;
    }
}    

你可能感兴趣的:(Java题解,算法)