题意:
给出一个堆叠后的表示,求从底向上的图片的堆叠顺序。
具体描述看题目。
解析:
先构图,然后dfs+拓扑
代码:
#pragma comment(linker, "/STACK:1677721600")
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cassert>
#include <iostream>
#include <algorithm>
#define pb push_back
#define mp make_pair
#define LL long long
#define lson lo,mi,rt<<1
#define rson mi+1,hi,rt<<1|1
#define Min(a,b) ((a)<(b)?(a):(b))
#define Max(a,b) ((a)>(b)?(a):(b))
#define mem(a,b) memset(a,b,sizeof(a))
#define FIN freopen("in.txt", "r", stdin)
#define FOUT freopen("out.txt", "w", stdout)
#define rep(i,a,b) for(int i=(a); i<=(b); i++)
#define dec(i,a,b) for(int i=(a); i>=(b); i--)
using namespace std;
const int mod = 1e9 + 7;
const double eps = 1e-8;
const double ee = exp(1.0);
const int inf = 0x3f3f3f3f;
const int maxn = 30 + 10;
const double pi = acos(-1.0);
int readT()
{
char c;
int ret = 0,flg = 0;
while(c = getchar(), (c < '0' || c > '9') && c != '-');
if(c == '-') flg = 1; else ret = c ^ 48;
while( c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c ^ 48);
return flg ? - ret : ret;
}
LL readTL()
{
char c;
int flg = 0;
LL ret = 0;
while(c = getchar(), (c < '0' || c > '9') && c != '-');
if(c == '-') flg = 1; else ret = c ^ 48;
while( c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c ^ 48);
return flg ? - ret : ret;
}
char maze[maxn][maxn];
int r, c;
int word_num;
int inDegree[maxn];
int g[maxn][maxn];
bool vis[maxn];
int lx, rx, uy, dy;
void search_bound(int x, int y)
{
char ch = maze[x][y];
lx = uy = inf;
rx = dy = -inf;
rep(i, 0, r - 1)
{
rep(j, 0, c - 1)
{
if (maze[i][j] == ch)
{
uy = Min(uy, i);
dy = Max(dy, i);
lx = Min(lx, j);
rx = Max(rx, j);
}
}
}
}
void build_map()
{
word_num = 0;
rep(i, 0, r - 1)
{
rep(j, 0, c - 1)
{
char ch = maze[i][j];
if (ch == '.' || inDegree[ch - 'A'] != -1)
continue;
word_num++;
inDegree[ch - 'A'] = 0;
search_bound(i, j);
rep(k, lx, rx)
{
if (maze[uy][k] != ch)
g[ch - 'A'][maze[uy][k] - 'A'] = 1;
if (maze[dy][k] != ch)
g[ch - 'A'][maze[dy][k] - 'A'] = 1;
}
rep(k, uy, dy)
{
if (maze[k][lx] != ch)
g[ch - 'A'][maze[k][lx] - 'A'] = 1;
if (maze[k][rx] != ch)
g[ch - 'A'][maze[k][rx] - 'A'] = 1;
}
}
}
rep(i, 0, 25)
{
rep(j, 0, 25)
{
if (g[i][j])
{
inDegree[j]++;
}
}
}
}
void dfs(int dep, char ans[])
{
if (dep == word_num)
{
ans[dep] = '\0';
printf("%s\n", ans);
return ;
}
rep(i, 0, 25)
{
if (inDegree[i] == 0 && !vis[i])
{
ans[dep] = i + 'A';
vis[i] = true;
rep(j, 0, 25)
{
if (g[i][j])
--inDegree[j];
}
dfs(dep + 1, ans);
vis[i] = false;
rep(j, 0, 25)
{
if (g[i][j])
++inDegree[j];
}
}
}
}
int main()
{
#ifdef LOCAL
FIN;
#endif // LOCAL
while (~scanf("%d%d", &r, &c))
{
rep(i, 0, r - 1)
{
scanf("%s", maze[i]);
}
mem(inDegree, -1);
mem(g, 0);
build_map();
mem(vis, false);
char ans[maxn];
dfs(0, ans);
}
return 0;
}