Saturday, April 18, 2015

UVa 101 - The Blocks Problem

// UVa 101 - The Blocks Problem

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int n, pos[25];
vector<int> pile[25];

void reboot(int a) {
	int i, from = pos[a];
	for (i = 0; i < pile[from].size(); i++)
		if (pile[from][i] == a)
			break;
	int newSize = i + 1;

	for (i = i + 1; i < pile[from].size(); i++) {
		int target = pile[from][i];
		pos[target] = target;
		pile[target].push_back(target);
	}
	pile[from].resize(newSize);
}

void put(int a, int b) {
	int i, from = pos[a], to = pos[b];
	for (i = 0; i < pile[from].size(); i++)
		if (pile[from][i] == a)
			break;
	int newSize = i;

	for (; i < pile[from].size(); i++) {
		pos[pile[from][i]] = to;
		pile[to].push_back(pile[from][i]);
	}
	pile[from].resize(newSize);
}

void printAll() {
	for (int i = 0; i < n; i++) {
		cout << i << ":";
		for (int j = 0; j < pile[i].size(); j++)
			cout << " " << pile[i][j];
		cout << endl;
	}
}

int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		pos[i] = i;
		pile[i].push_back(i);
	}

	while (true) {
		string move, prep;
		cin >> move;
		if (move == "quit")
			break;
		int a, b;
		cin >> a >> prep >> b;

		if (pos[a] == pos[b])
			continue;

		if (move == "move" && prep == "onto") {
			reboot(a);
			reboot(b);
		} else if (move == "move" && prep == "over") {
			reboot(a);
		} else if (move == "pile" && prep == "onto") {
			reboot(b);
		}
		put(a, b);
	}

	printAll();

	return 0;
}

No comments:

Post a Comment