# Yuki 470 Inverse S+T Problem ( 2SAT, Dummy Constraints )

No.470 Inverse S+T Problem - yukicoder

N ≤ 1e5
sigma: { 'a'~'z', 'A'~'Z' }

1. SCC 的時候忘記用 rG
2. 忘記用拓撲序決定 sat，接近根的盡量給 false ( 因為如果上方不必要的 true 太多，下方就要產生更多不必要的 true，反之不存在依賴關係 )。

O( | sigma | * | sigma | ) / O( | sigma | )

```#include <bits/stdc++.h>
using namespace std;

const int MAXN = 52;

int N;
string S[ MAXN * 2 ];

vector< int > G[ MAXN * 2 ], rG[ MAXN * 2 ];

void dfs_topo( int u, vector< int > &stk, vector< int > &vis ) {
for( int v : G[ u ] ) {
if( vis[ v ] ) continue;
vis[ v ] = 1;
dfs_topo( v, stk, vis );
}
stk.emplace_back( u );
}

void dfs_ksrj( int u, vector< int > &scc, int scc_id ) {
for( int v : rG[ u ] ) {
if( scc[ v ] ) continue;
scc[ v ] = scc_id;
dfs_ksrj( v, scc, scc_id );
}
}

signed main() {
ios::sync_with_stdio( 0 );
cin >> N;
if( N > MAXN ) {
cout << "Impossible" << endl;
exit( 0 );
}
for( int i = 0; i < N; ++i ) {
cin >> S[ i ];
}
for( int i = 0; i < N; ++i ) {
for( int j = 0; j < N; ++j ) {
if( i == j ) continue;
if( S[ i ][ 0 ] == S[ j ][ 0 ] or S[ i ].substr( 1, 2 ) == S[ j ].substr( 1, 2 ) ) {
G[ i ].emplace_back( N + j );
rG[ N + j ].emplace_back( i );
}
if( S[ i ][ 0 ] == S[ j ][ 2 ] or S[ i ].substr( 1, 2 ) == S[ j ].substr( 0, 2 ) ) {
G[ i ].emplace_back( j );
rG[ j ].emplace_back( i );
}
if( S[ i ][ 2 ] == S[ j ][ 0 ] or S[ i ].substr( 0, 2 ) == S[ j ].substr( 1, 2 ) ) {
G[ N + i ].emplace_back( N + j );
rG[ N + j ].emplace_back( N + i );
}
if( S[ i ][ 2 ] == S[ j ][ 2 ] or S[ i ].substr( 0, 2 ) == S[ j ].substr( 0, 2 ) ) {
G[ N + i ].emplace_back( j );
rG[ j ].emplace_back( N + i );
}
}
}
int scc_cnt = 0;
vector< int > stk, scc( N * 2 );
{
vector< int > vis( N * 2 );
for( int i = 0; i < N * 2; ++i ) {
if( vis[ i ] ) continue;
vis[ i ] = 1;
dfs_topo( i, stk, vis );
}
for( int i = N * 2 - 1; i >= 0; --i ) {
if( scc[ stk[ i ] ] ) continue;
scc[ stk[ i ] ] = ++scc_cnt;
dfs_ksrj( stk[ i ], scc, scc_cnt );
}
}
for( int i = 0; i < N; ++i ) {
if( scc[ i ] == scc[ N + i ] ) {
cout << "Impossible" << endl;
exit( 0 );
}
}
vector< int > sat( scc_cnt + 1 );
for( int i = N * 2 - 1; i >= 0; --i ) {
int u = stk[ i ];
int v = stk[ i ] >= N ? stk[ i ] - N : stk[ i ] + N;
if( sat[ scc[ u ] ] ) {
sat[ scc[ v ] ] = 3 - sat[ scc[ u ] ];
} else if( sat[ scc[ v ] ] ) {
sat[ scc[ u ] ] = 3 - sat[ scc[ v ] ];
} else {
sat[ scc[ u ] ] = 2;
sat[ scc[ v ] ] = 1;
}
}
for( int i = 0; i < N; ++i ) {
if( sat[ scc[ i ] ] == 1 ) {
cout << S[ i ][ 0 ] << " " << S[ i ].substr( 1, 2 ) << "\n";
} else {
cout << S[ i ].substr( 0, 2 ) << " " << S[ i ][ 2 ] << "\n";
}
}
return 0;
}
```