题目链接:http://codeforces.com/gym/102219/problem/J
Time limit per test 1.0 s Memory limit per test 256 MB
Description
You are given 5 different sizes of kitchen plates. Each plate is marked with a letter A, B, C, D, or E. You are given 5 statements comparing two different plates, you need to rearrange the plates from smallest size to biggest size. For example: the sizes of these plates.
Input
The input consist of 5 lines. In each line there will be 3 characters, the first and last character will be either A, B, C, D, or E and the middle character will be either > or < describing the comparison between two plates sizes. No two plates will be equal.
Output
The output consist of 5 characters, the sorted order of balls from smallest to biggest plate. Otherwise, if the statements are contradicting print impossible. If there are multiple answers, print any of them.
Examples
input
D>B
A>D
E<C
A>B
B>C
output
ECBDA
input
B>E
A>B
E>A
C<B
D<B
output
impossible
Problem solving report:
Description: 给你ABCDE的相对大小,判断能否判断出它们的大小顺序,如果能,就从小到大输出,否则就输出‘impossible’。
Problem solving: 建边,然后就是裸的拓扑排序。
Accepted Code:
/*
* @Author: lzyws739307453
* @Language: C++
*/
#include <bits/stdc++.h>
using namespace std;
vector <int> spt;
void TopSort(vector <int> G[], int degree[]) {
queue <int> Q;
for (int i = 0; i < 5; i++)
if (!degree[i])
Q.push(i);
while (!Q.empty()) {
int u = Q.front();
Q.pop();
spt.push_back(u);
for (int i = 0; i < G[u].size(); i++) {
degree[G[u][i]]--;
if (!degree[G[u][i]])
Q.push(G[u][i]);
}
}
}
int main() {
int degree[5] = {0};
vector <int> G[5];
for (int i = 0; i < 5; i++) {
char u, v, op;
scanf(" %c%c%c", &u, &op, &v);
int a = u - 'A', b = v - 'A';
if (op != '<')
swap(a, b);
degree[b]++;
G[a].push_back(b);
}
TopSort(G, degree);
if (spt.size() < 5)
printf("impossible\n");
else {
for (int i = 0; i < spt.size(); i++)
printf("%c", spt[i] + 'A');
printf("\n");
}
return 0;
}