-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1202.cpp
More file actions
68 lines (65 loc) · 1.81 KB
/
1202.cpp
File metadata and controls
68 lines (65 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
Solution()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
string smallestStringWithSwaps(string s, vector<vector<int>> &pairs)
{
string s_copy = s.substr();
cout << endl;
vector<bool> visited(s.length(), false);
vector<vector<int>> adj(s.length());
for (auto p : pairs)
{
adj[p[0]].push_back(p[1]);
adj[p[1]].push_back(p[0]);
}
for (int i = 0; i < s.length(); ++i)
{
if (!visited[i])
{
vector<char> tmpString;
vector<int> tmpIndex;
queue<int> q;
q.push(i);
visited[i] = true;
while (!q.empty())
{
int u = q.front();
q.pop();
tmpString.push_back(s[u]);
tmpIndex.push_back(u);
for (auto v : adj[u])
{
if (!visited[v])
{
q.push(v);
visited[v] = true;
}
}
}
sort(tmpString.begin(), tmpString.end());
sort(tmpIndex.begin(), tmpIndex.end());
int size = tmpString.size();
for (int index = 0; index < size; ++index) {
s_copy[tmpIndex[index]] = tmpString[index];
}
}
}
return s_copy;
}
};
int main()
{
Solution s;
string str = "dcab";
vector<vector<int>> pairs = {{0, 3}, {1, 2}, {0, 2}};
cout << s.smallestStringWithSwaps(str, pairs) << endl;
return 0;
}