Decorating The Pastures
鏈接:https://ac.nowcoder.com/acm/contest/3888/G
來源:牛客網(wǎng)
?
時間限制:C/C++ 1秒,其他語言2秒
空間限制:C/C++ 262144K,其他語言524288K
64bit IO Format: %lld
題目描述
Farmer John has N (1 <= N <= 50,000) pastures, conveniently numbered 1...N,
connected by M (1 <= M <= 100,000) bidirectional paths. Path i connects
pasture A_i (1 <= A_i <= N) to pasture B_i (1 <= B_i <= N) with A_i != B_i.
It is possible for two paths to connect between the same pair of pastures.
Bessie has decided to decorate the pastures for FJ's birthday. She wants to
put a large sign in each pasture containing either the letter 'F' or 'J',
but in order not to confuse FJ, she wants to be sure that two pastures are
decorated by different letters if they are connected by a path.
The sign company insists on charging Bessie more money for an 'F' sign than
a 'J' sign, so Bessie wants to maximize the number of 'J' signs that she
uses. Please determine this number, or output -1 if there is no valid way
to arrange the signs.
輸入描述:
* Line 1: Two integers N and M.* Lines 2..M+1: Two integers, A_i and B_i indicating that there is a bidirectional path from A_i to B_i.輸出描述:
* Line 1: A single integer indicating the maximum number of 'J' signs that Bessie can use. If there is no valid solution for arranging the signs, output -1.示例1
輸入
4 4 1 2 2 3 3 4 4 1輸出
2分析:給定一個無向圖,用 'F' 和 'J' 進行 01 染色,求max(0節(jié)點數(shù)量, 1節(jié)點數(shù)量)
遍歷圖中每一個點,對未進行染色的點定為起點設(shè)定一種顏色,然后從該點開始進行 dfs 染色,每個子圖的 dfs 結(jié)束后對子圖的最大染色數(shù)(F、J中的最大一種)進行累加。
注意奇數(shù)環(huán),如 1 -- 2 --- 3 -- 1 ,這種就是 -1 的情況,因此需要在 dfs 是判斷下一個點的顏色是否跟當(dāng)前點相同,相同則為奇數(shù)環(huán)。
代碼:
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.regex.Pattern;public class Main {public static Scanner in = new Scanner(System.in);public static PrintWriter out = new PrintWriter(System.out);public static int t, n, m, ans, k, u, v, sumF, sumJ;public static int[] color = new int[50010];public static List<Integer>[] to = new ArrayList[50010];public static void main(String args[]) {n = in.nextInt();m = in.nextInt();for (int i = 1; i <= n; i++) {to[i] = new ArrayList();color[i] = 0;}for (int i = 0; i < m; i++) {u = in.nextInt();v = in.nextInt();to[u].add(v);to[v].add(u);}ans = 0;for (int i = 1; i <= n; i++) {if (color[i] != 0) {continue;}color[i] = 1;sumF = 1;sumJ = 0;dfs(i);if (sumF == -1 || sumJ == -1) {ans = -1;break;}ans += Math.max(sumF, sumJ);}out.println(ans);out.flush();out.close();}static void dfs(int p) {int len = to[p].size();for (int i = 0; i < len; i++) {if (color[to[p].get(i)] == color[p]) {sumF = -1;return;}if (color[to[p].get(i)] == 0) {if (sumF == -1) {return;}if (color[p] == 1) {color[to[p].get(i)] = 2;sumJ++;} else {color[to[p].get(i)] = 1;sumF++;}dfs(to[p].get(i));}}} }?
總結(jié)
以上是生活随笔為你收集整理的Decorating The Pastures的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 山东英才学院春季高考计算机专业录取分数线
- 下一篇: Antv/g6 - 鼠标事件