士兵排队问题
Description
有N个士兵(1≤N≤26),编号依次为A,B,C,…,队列训练时,指挥官要把一些士兵从高到矮一次排成一行,但现在指挥官不能直接获得每个人的身高信息,只能获得“P1比P2高”这样的比较结果(P1、P2∈A,B,C,…,Z,记为 P1>P2),如”A>B”表示A比B高。
请编一程序,根据所得到的比较结果求出一种符合条件的排队方案。
(注:比较结果中没有涉及的士兵不参加排队)
Input
比较结果从文本文件中读入(文件由键盘输入),每个比较结果在文本文件中占一行。
Output
若输入数据无解,打印“No Answer!”信息,否则从高到矮一次输出每一个士兵的编号,中间无分割符,并把结果写入文本文件中,文件由键盘输入:
Sample Input 1
A>B B>D F>B F<A
Sample Output 1
AFBD
解题思路:这题的核心是拓扑排序和优先级队列。先将输入的信息建立出一张图(用邻接表实现),再结合拓扑排序和优先级队列以及STL里的关联容器map解决问题。
源代码:
#include<iostream>
#include<vector>
#include<map>
#include<queue>
using namespace std;
struct Enode
{
char name;
Enode* next;
};
struct Vnode
{
char name;
int in;
Enode* first;
Vnode() {
in = 0;
first = nullptr;
}
};
class ALGraph
{
private:
vector<Vnode> v;
map<char, int> m;
int vN, eN;
public:
ALGraph() {
Vnode t;
string input;
Enode* s = nullptr;
int n = 0;//顶点表的下标
while (cin >> input) {
int k = 0;//判断顶点表中是否已经存在该顶点,0为不存在,1为存在
for (int i = 0; i < v.size(); i++) {
if (v[i].name == input[0]) {
k = 1;
i = v.size();
}
}
if (!k) {
t.name = input[0];
v.push_back(t);
m[input[0]] = n;
n++;
}
k = 0;
for (int i = 0; i < v.size(); i++) {
if (v[i].name == input[2]) {
k = 1;
i = v.size();
}
}
if (!k) {
t.name = input[2];
v.push_back(t);
m[input[2]] = n;
n++;
}
s = new Enode;
s->name = input[2];
s->next = v[m[input[0]]].first;
v[m[input[0]]].first = s;
v[m[input[2]]].in++;
}
TopSort();
}
void TopSort() {
string result = "";
int i, count = 0;
char j, k;
Enode* p = nullptr;
queue<char> q;
priority_queue<char, vector<char>, greater<char> >T;
for (int i = 0; i < v.size(); i++) {
if (v[i].in == 0) {
T.push(v[i].name);
}
}
while (!T.empty()) {
q.push(T.top());
T.pop();
}
while (!q.empty()) {
j = q.front();
q.pop();
result += j;
count++;
p = v[m[j]].first;
while (p != nullptr) {
k = p->name;
v[m[k]].in--;
if (v[m[k]].in == 0) {
T.push(k);
}
p = p->next;
}
while (!T.empty()) {
q.push(T.top());
T.pop();
}
}
if (count < v.size()) cout << "No Answer!";
else cout << result;
}
};
int main()
{
ALGraph* Q = new ALGraph();
return 0;
}