京东c++ 2AC代码(并查集+暴力)
第一题用并查集解决
class UnionFind { private: vector<int> parent; vector<int> sz; int count; int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public: UnionFind(int count) { parent.resize(count); sz.resize(count); this->count = count; for (int i = 0; i < count; i++) { parent[i] = i; sz[i] = 1; } } ~UnionFind() { } bool isConnected(int p, int q) { return find(p) == find(q); } void unionElements(int p, int q) { int pRoot = find(p); int qRoot = find(q); if (pRoot == qRoot) return; if (sz[pRoot] < sz[qRoot]) { parent[pRoot] = qRoot; sz[qRoot] += sz[pRoot]; } else { parent[qRoot] = pRoot; sz[pRoot] += sz[qRoot]; } } }; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int n, m; cin >> n >> m; vector<vector<int>> g(n, vector<int>(n, 0)); for (int j = 0; j < m; j++) { int x, y; cin >> x >> y; g[x - 1][y - 1] = 1; g[y - 1][x - 1] = 1; } UnionFind uf(n + 1); bool isBad = false; for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (x != y && x < y) { if (g[x][y] == 0) { uf.unionElements(x, y); } } } } for (int x = 0; x < n; x++) { for (int y = 0; y < n; y++) { if (x != y && x < y) { if (g[x][y] == 1 && uf.isConnected(x, y)) { cout << "No" << endl; isBad = true; break; } } } if (isBad) break; } if (!isBad) { cout << "Yes" << endl; } } return 0; }
第二题直接对a排序后遍历
struct Thing { int a; int b; int c; Thing(int x, int y, int z): a(x), b(y), c(z) { } }; bool lessc(const Thing& a, const Thing& b) { return a.a < b.a; } int main() { int n, count(0); cin >> n; vector<Thing> things; for (int i = 0; i < n; i++) { int x, y, z; cin >> x >> y >> z; things.push_back(Thing(x, y, z)); } sort(things.begin(), things.end(), lessc); for (auto it = things.begin(); it != things.end(); ++it) { for (auto it2 = it + 1; it2 != things.end(); ++it2) { if (it->a < it2->a && it->b < it2->b && it->c < it2->c) { count++; break; } } } cout << count << endl; }#京东##笔试题目#