Codeforces #360 Div2 C
解法
この問題で出てくる頂点被覆は問題文に書いてある通りで、「あるグラフのすべての各辺について、その辺につながっている2つの頂点どちらかまたは両方の頂点を選択した頂点の集合」がグラフに含まれていることを頂点被覆という
参考:
頂点被覆 - Wikipedia
今回の問題の場合は与えれたグラフからAとBという互いに素な頂点の集合に分けるので、
AとBの独立集合に分けられるかという問題を2部グラフが出来るかという問題として考える。
ということは、与えられたグラフに含まれるすべての各辺につながれている頂点2つは必ず、
AとBの集合に一つずつ振り分けられる。
2部グラフの判定には蟻本のコードを写経しました。
ソースコード
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.NoSuchElementException; public class C { int N, M; ArrayList<Integer>[] graph; int[] color; public boolean dfs(int n,int c){ color[n] = c; for(int next : graph[n]){ if(color[next] != 0){ if(color[n] == color[next]){ return false; } }else{ if(!dfs(next,-c)){ return false; } } } return true; } public void solve() { N = nextInt(); M = nextInt(); graph = new ArrayList[N]; for (int i = 0; i < N; i++) { graph[i] = new ArrayList<Integer>(); } color = new int[N]; for (int i = 0; i < M; i++) { int u = nextInt() - 1; int v = nextInt() - 1; graph[u].add(v); graph[v].add(u); } for(int i = 0;i < N;i++){ if(color[i] == 0){ if(!dfs(i,1)){ out.println(-1); return; } } } ArrayList<Integer> a,b; a = new ArrayList<Integer>(); b = new ArrayList<Integer>(); for(int i = 0;i < N;i++){ if(color[i] == 1){ a.add(i + 1); }else{ b.add(i + 1); } } out.println(a.size()); for(int i = 0;i < a.size();i++){ if(i != 0)out.print(" "); out.print(a.get(i)); } out.println(); out.println(b.size()); for(int i = 0;i < b.size();i++){ if(i != 0)out.print(" "); out.print(b.get(i)); } out.println(); } public static void main(String[] args) { out.flush(); new C().solve(); out.close(); } /* Input */ private static final InputStream in = System.in; private static final PrintWriter out = new PrintWriter(System.out); private final byte[] buffer = new byte[2048]; private int p = 0; private int buflen = 0; private boolean hasNextByte() { if (p < buflen) return true; p = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; return true; } public boolean hasNext() { while (hasNextByte() && !isPrint(buffer[p])) { p++; } return hasNextByte(); } private boolean isPrint(int ch) { if (ch >= '!' && ch <= '~') return true; return false; } private int nextByte() { if (!hasNextByte()) return -1; return buffer[p++]; } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = -1; while (isPrint((b = nextByte()))) { sb.appendCodePoint(b); } return sb.toString(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }