Skip to content

Instantly share code, notes, and snippets.

@rajatkhanduja
Created November 5, 2012 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajatkhanduja/4016849 to your computer and use it in GitHub Desktop.
Save rajatkhanduja/4016849 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <algorithm>
#include <set>
#include <queue>
#include <cstring>
#include <cassert>
using namespace std;
void sccSetInsertions (set<int>& indexSet, set<int>& valSet, const int& i, const int& val)
{
indexSet.insert (i);
valSet.insert(val);
}
void checkSCCMembers(const int& i, const int& k, int *arr, int *swaps, queue<int>& bfsQ,
set<int>& sccVals, set<int>& sccIndices, int *considered)
{
for (int j = 0; j < k; j++)
{
if (swaps[j] == 1)
{
if (considered[j] == 0)
{
bfsQ.push(j);
sccSetInsertions(sccIndices, sccVals, j, arr[j]);
considered[j] = 1;
}
}
}
}
int main (void)
{
int k, i, j;
scanf ("%d", &k);
int arr[k];
int swaps[k][k];
for(i = 0; i < k; i++)
{
cin >> arr[i];
}
char c;
for(i = 0; i < k; i++)
{
for (j = 0; j < k; j++)
{
cin >> c;
assert (c == 'Y' || c == 'N');
swaps[i][j] = (c == 'Y');
}
}
set<int> sccIndices, sccVals;
queue<int> bfsQ;
int considered[k], tmp;
bzero (considered, sizeof(int) * k);
for (i = 0; i < k; i++)
{
if (considered[i] == 1)
continue;
else
{
sccSetInsertions(sccIndices, sccVals, i, arr[i]);
considered[i] = 1;
}
checkSCCMembers (i, k, arr, swaps[i], bfsQ, sccVals, sccIndices, considered);
while (bfsQ.size() > 0)
{
tmp = bfsQ.front();
bfsQ.pop();
checkSCCMembers(tmp, k, arr, swaps[tmp], bfsQ, sccVals, sccIndices, considered);
}
set<int>::iterator itVal = sccVals.begin(), itIndex = sccIndices.begin();
for(; itIndex != sccIndices.end(); itIndex++, itVal++)
{
arr[*itIndex] = *itVal;
}
sccIndices.clear();
sccVals.clear();
}
for (i = 0; i < k; i++)
{
cout << arr[i];
if (i != k - 1)
cout << " ";
}
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment