題目來源java
集裝箱運輸貨物時,咱們必須特別當心,不能把不相容的貨物裝在一隻箱子裏。好比氧化劑絕對不能跟易燃液體同箱,不然很容易形成爆炸。ios
本題給定一張不相容物品的清單,須要你檢查每一張集裝箱貨品清單,判斷它們是否能裝在同一只箱子裏。c++
輸入第一行給出兩個正整數:N (≤104) 是成對的不相容物品的對數;M (≤100) 是集裝箱貨品清單的單數。數組
隨後數據分兩大塊給出。第一塊有 N 行,每行給出一對不相容的物品。第二塊有 M 行,,格式以下:安全
K G[1] G[2] ... G[K]
其中 K
(≤1000) 是物品件數,G[i]
是物品的編號。簡單起見,每件物品用一個 5 位數的編號表明。兩個數字之間用空格分隔。spa
對每箱貨物清單,判斷是否能夠安全運輸。若是沒有不相容物品,則在一行中輸出 Yes
,不然輸出 No
。code
6 3 20001 20002 20003 20004 20005 20006 20003 20001 20005 20004 20004 20006 4 00001 20004 00002 20003 5 98823 20002 20003 20006 10010 3 12345 67890 23333
No Yes Yes
輸入N,M,分別爲:內存
接下來N行,每行輸入兩個數,表示不相容的物品ci
接下來M行,每行給出一箱貨物的清單get
思路:
一開始用了unordered_map<int, unordered_map<int, int>> m
來存放,超內存了
後來考慮用一個map和vector數組來存放不相容的物品
好比下面這個輸入,咱們能夠用unordered_map<int, vector<int>> m
來存放
把第一第二個物品都放入map中,記錄不相容的物品
20001 20002 20003 20004 20005 20006 20003 20001 20005 20004 20004 20006
這樣就知道了每一個物品和哪些東西不相容:
key(int) -> value(vector<int>) m[20001] -> 20002, 20003 m[20002] -> 20001 m[20003] -> 20001, 20004 m[20004] -> 20003, 20005, 20006 m[20005] -> 20004, 20006 m[20006] -> 20004, 20005
對於接下來的M行輸入,每行的輸入存入一個數組res
4 00001 20004 00002 20003 5 98823 20002 20003 20006 10010 3 12345 67890 23333
好比第一行的4 00001 20004 00002 20003
存入數組res
獲得:00001 20004 00002 20003
同時用一個數組arr
記錄這4個id的出現狀況
好比(用下標記錄):
arr[00001] = 1 arr[20004] = 1 arr[00002] = 1 arr[20003] = 1
遍歷數組res
,在unordered_map
中,獲取到與res[i]
不相容的物品
m[res[i]]
就是不相容的物品,這是一個vector
數組
res[i] = 20001
:
m[res[i]] = m[20001] -> 20002, 20003
遍歷這個數組,取出裏面的元素x
arr[x] == 1
:就說明有不相容的物品#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <string> #include <stack> #include <cmath> #include <map> using namespace std; int main() { short N; // 成對的,不相容物品的對數 short M; // 集裝箱貨品清單的單數 unordered_map<int, vector<int>>m; cin >> N >> M; for (int i = 0; i < N; ++i) { int first, second; cin >> first >> second; m[first].push_back(second); m[second].push_back(first); } while (M--) { bool flag = false; int cnt; cin >> cnt; vector<int> res(cnt); int arr[100001] = { 0 }; for (int i = 0; i < cnt; ++i) { cin >> res[i]; arr[res[i]] = 1; } for (int i = 0; i < cnt; ++i) { for (int j = 0; j < m[res[i]].size(); ++j) { // m[res[i]]是一個vector數組 // m[res[i]][j]是vecotr裏的元素 int x = m[res[i]][j]; if (arr[x] == 1) { flag = true; } } } if (flag) { printf("No\n"); } else { printf("Yes\n"); } } return 0; }
// TODO