#2018jd秋招兩道編程題如下:
##第一道
給定一張包含N個點、M條邊的無向圖,每條邊連接兩個不同的點,且任意兩點間最多隻有一條邊。對於這樣的簡單無向圖,如果能將所有點劃分成若干個集合,使得任意兩個同一集合內的點之間沒有邊相連,任意兩個不同集合內的點之間有邊相連,則稱該圖爲完全多部圖。現在你需要判斷給定的圖是否爲完全多部圖。
思路:
1、採用鄰接矩陣封裝數據;
2、通過節點的度來判斷是否達到要求;
3、題中的同一集合中沒有相連邊,不同集合中的節點有邊相連。=》同一集合中各節點度的度必須相等,且節點互不相連。。
輸入: 第一行表示數據的組數(即圖的個數),第二行表示 N個節點及採用節點表示的邊的條數M。例如 2 3表示節點2和節點3之間有一條邊。
number
N M
.
.
N M
.
.
輸出:表示輸入的圖是否爲完全多部圖
YES | NO
import java.util.Scanner;
public class MainFirst {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
//遍歷多個圖
while (T > 0) {
//遍歷某個圖的數據
//圖的節點數
int N = scan.nextInt();
//圖的邊數
int M = scan.nextInt();
//X, Y表示節點
int X, Y;
//通過鄰接矩陣來表示圖
int[][] edge = new int[N + 1][N + 1];
//通過遍歷來填充鏈接矩陣中的元素
for (int i = 0; i < M; i++) {
X = scan.nextInt();
Y = scan.nextInt();
//無向圖是一個對稱陣
edge[X][Y] = 1;
edge[Y][X] = 1;
}
//判斷
String s = isCover(edge, N);
//輸出結果
System.out.println(s);
T--;
}
}
//判斷是否爲完全多部圖
public static String isCover(int[][] edge, int N) {
String s = "Yes";
//計算各節點的度
int[] sum = new int[N + 1];
//通過對鄰接矩陣的列求和可以得到對應節點的 度
for (int i = 1; i < N + 1; i++) {
for (int j = 1; j < N + 1; j++) {
sum[i] += edge[i][j];
}
}
//遍歷所有可能相連的節點,通過排除與題意矛盾的情況的到最後的正確答案
for (int i = 1; i < N + 1; i++) {
for (int j = 1; j < N + 1; j++) {
//若節點不相連 =》 必須在同一集合中
if (edge[i][j] == 0) {
//同一集合,如果度不相等也就意味這 j可以連接的節點(其它集合中),i無法連接,
//這與題意中:任意兩個不同集合內的點之間有邊相連。相矛盾
if (sum[j] != sum[i])
s = "No";
}
}
}
return s;
}
}
##第二道
現有n個物品,每個物品有三個參數 ai , bi , ci ,定義i物品不合格品的依據是 : 若存在物品 j , 且aj>ai , bj>bi ,cj>ci,則稱i物品爲不合格品。 現給出n個物品的a,b,c參數,請你求出不合格品的數量。
> 輸入: 第一行數據爲物品的數目n;接下來n行數據爲n個物品的三個參數 a b c
3
1 2 3
7 6 5
3 6 7
>輸出:產品的不合格數
1
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MainSecond {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = Integer.parseInt(cin.nextLine());
//保存物品的格式<編號,a-b-c>
Map<Integer, String> goods = new HashMap<Integer, String>();
// 保存物品
for (int i = 0; i < n; i++) {
String[] params = cin.nextLine().split(" ");
goods.put(i, params[0] + "-" + params[1] + "-" + params[2]);
}
//不合格的物品數量
int count = 0;
// 比較物品
for (int i = 0; i < n; i++) {
//得到需要判斷的物品的三個參數
String[] params = goods.get(i).split("-");
//將需要判斷的物品參數與其餘的物品參數進行比較
for (int j = 0; j < n; j++) {
//表示比較與被比較的物品爲同一物品,則繼續循環
if (j == i) {
continue;
}
String[] p = goods.get(j).split("-");
//根據題意判斷物品是否合格,不合格則直接跳出
if (Integer.parseInt(params[0]) < Integer.parseInt(p[0])
&& Integer.parseInt(params[1]) < Integer.parseInt(p[1])
&& Integer.parseInt(params[2]) < Integer.parseInt(p[2])) {
count++;
break;
}
}
}
//輸出不合格數目
System.out.println(count);
}
}