51 problems solved
This commit is contained in:
40
CSES - CSES Problem Set/Graph_Algorithms/Building_Roads.cpp
Normal file
40
CSES - CSES Problem Set/Graph_Algorithms/Building_Roads.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
// Building Roads
|
||||
|
||||
#include<bits/stdc++.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
void dfs(vector<vector<int>> &g, int s, vector<bool> &v) {
|
||||
v[s] = true;
|
||||
for (auto e: g[s]) {
|
||||
if (!v[e]) dfs(g, e, v);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
int n, m; cin >> n >> m;
|
||||
vector<vector<int>> g(n);
|
||||
for (int i{}; i < m; i++) {
|
||||
int a, b;
|
||||
cin >> a >> b;
|
||||
a--; b--;
|
||||
g[a].push_back(b);
|
||||
g[b].push_back(a);
|
||||
}
|
||||
int count = -1;
|
||||
vector<pair<int, int>> roads;
|
||||
vector<bool> v(n);
|
||||
for (int i{}; i < n; i++) {
|
||||
if (v[i]) continue;
|
||||
count ++;
|
||||
dfs(g, i, v);
|
||||
if (i > 0) roads.push_back({i, i - 1});
|
||||
}
|
||||
|
||||
cout << count << endl;
|
||||
for (auto [x, y]: roads) {
|
||||
cout << x+1 << " " << y + 1 << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
44
CSES - CSES Problem Set/Graph_Algorithms/Counting_Rooms.cpp
Normal file
44
CSES - CSES Problem Set/Graph_Algorithms/Counting_Rooms.cpp
Normal file
@@ -0,0 +1,44 @@
|
||||
// Counting Rooms
|
||||
|
||||
#include<bits/stdc++.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
void dfs(vector<vector<vector<pair<int, int>>>> &m, pair<int, int> s, vector<vector<bool>> &v) {
|
||||
v[s.first][s.second] = true;
|
||||
for (auto e: m[s.first][s.second]) {
|
||||
if (!v[e.first][e.second]) dfs(m, e, v);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int n, m; cin >> n >> m;
|
||||
// map<pair<int, int>, vector<pair<int, int>>> map1;
|
||||
vector<vector<vector<pair<int, int>>>> map1(n, vector<vector<pair<int, int>>>(m));
|
||||
vector<string> in;
|
||||
for (int i{}; i < n; i++) {
|
||||
string s; cin >> s; in.push_back(s);
|
||||
}
|
||||
for (int i{}; i < n; i++) {
|
||||
for (int j{}; j < m; j++) {
|
||||
if (in[i][j] == '#') continue;
|
||||
if (i > 0 && in[i-1][j] == '.') map1[i][j].push_back({i-1, j});
|
||||
if (i < n - 1 && in[i+1][j] == '.') map1[i][j].push_back({i+1, j});
|
||||
if (j > 0 && in[i][j-1] == '.') map1[i][j].push_back({i, j-1});
|
||||
if (j < m - 1 && in[i][j+1] == '.') map1[i][j].push_back({i, j+1});
|
||||
}
|
||||
}
|
||||
// set<pair<int, int>> v;
|
||||
vector<vector<bool>> v(n, vector<bool>(m, false));
|
||||
int count = 0;
|
||||
for (int i{}; i < n; i++) {
|
||||
for (int j{}; j < m; j++) {
|
||||
if (in[i][j] == '#') continue;
|
||||
if (v[i][j]) continue;
|
||||
count++;
|
||||
dfs(map1, {i, j}, v);
|
||||
}
|
||||
}
|
||||
cout << count << endl;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user