Saturday, June 6, 2015

UVa 124 - Following Orders

// UVa 124 - Following Orders

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;

string v, sol;
int parents[26];
bool lnk[26][26];
bool yet[26];

void comb(int n) {
	if (n == v.length()) {
		cout << sol << endl;
		return;
	}
	for (int i = 0; i < v.length(); i++)
		if (parents[v[i]] == 0 && yet[v[i]]) {
			for (int j = 0; j < v.length(); j++)
				if (lnk[v[i]][v[j]])
					parents[v[j]]--;
			yet[v[i]] = false;
			sol += (v[i] + 'a');
			comb(n + 1);
			sol.erase(sol.length() - 1, 1);
			yet[v[i]] = true;
			for (int j = 0; j < v.length(); j++)
				if (lnk[v[i]][v[j]])
					parents[v[j]]++;
		}
}

int main() {
	string vvars, cons;
	int t = 0;
	while (getline(cin, vvars)) {
		v = "";
		for (int i = 0; i < vvars.length(); i += 2)
			v += (vvars[i] - 'a');
		sort(v.begin(), v.end());
		getline(cin, cons);
		memset(lnk, false, sizeof(lnk));
		memset(parents, 0, sizeof(parents));
		for (int i = 0; i < cons.length(); i += 4) {
			char a = cons[i] - 'a';
			char b = cons[i + 2] - 'a';
			lnk[a][b] = true;
			parents[b]++;
		}

		if (t > 0)
			cout << endl;

		memset(yet, true, sizeof(yet));
		sol = "";
		comb(0);

		t++;
	}
	return 0;
}

No comments:

Post a Comment