Problem:
Deadlock Detection
In concurrent processing environments, a deadlock is an undesirable
situation where two or more threads are mutually waiting for others to
finish using some resources and cannot proceed further.

Your task is to detect whether there is any possibility of deadlocks
when multiple threads try to execute a given instruction sequence concurrently.
The instruction sequence consists of characters '
u
' or digits from
'
0
' to '
9
', and each of them represents one instruction.
10 threads are trying to execute the same single instruction sequence.
Each thread starts its execution from the beginning of the sequence and
continues in the given order, until all the instructions are
executed.
There are 10 shared resources called
locks
from
L
0
to
L
9
.
A digit
k
is the instruction for
acquiring
the lock
L
k
.
After one of the threads acquires a lock
L
k
,
it is kept by the thread until it is
released
by the instruction '
u
'.
While a lock is kept, none of the threads, including one already acquired it,
cannot newly acquire the same lock
L
k
.
Precisely speaking, the following steps are repeated until all threads
finish.
One thread that has not finished yet is chosen arbitrarily.
The chosen thread tries to execute the next instruction that is not executed yet.
If the next instruction is a digit
k
and
		the lock
L
k
is not kept by any thread,
		the thread executes the instruction
k
and acquires
L
k
.
If the next instruction is a digit
k
and
		the lock
L
k
is already kept by some thread,
		the instruction
k
is not executed.
If the next instruction is '
u
',
		the instruction is executed and
all
the locks currently kept by the thread
		are released.
After executing several steps, sometimes, it falls into the situation 
that the next instructions
of all unfinished threads are for acquiring already kept locks.
Once such a situation happens, no instruction will ever be executed no 
matter which thread is chosen. This situation is called a
deadlock
.
There are instruction sequences for which threads can never reach a
deadlock regardless of the execution order.
Such instruction sequences are called
safe
.
Otherwise, in other words, if there exists one or more execution orders
that lead to a deadlock, the execution sequence is called
unsafe
.

Your task is to write a program that tells whether the given instruction sequence is safe or unsafe.
Input
The input consists of at most 50 datasets, each in the following format.
n
s
n
is the length of the instruction sequence and
s
is a string representing the sequence.
n
is a positive integer not exceeding 10,000.
Each character of
s
is either a digit ('
0
' to '
9
') or '
u
',
and
s
always ends with '
u
'.
The end of the input is indicated by a line with a zero.
Output
For each dataset, if the given instruction sequence is safe, then print
"SAFE"
in a line.
If it is unsafe, then print
"UNSAFE"
in a line.
Sample Input
11
01u12u0123u
6
01u10u
8
201u210u
9
01u12u20u
3
77u
12
9u8u845u954u
0
Output for the Sampl
...(truncated)

Submitted solutions:

code_snippet: #include <iostream>
#include <string>
#include <cstring>
using namespace std;
#define rep(i,n) for(int i = 0; i < n; i++)
bool dp[1024][10];
void solve(int n){
    string s;
    cin >> s;
    int state = 0;
    memset(dp,0,sizeof(dp));
    rep(i,n-2){
        if(s[i] == 'u'){
            state = 0;
            continue;
        }
        state |= 1<<(s[i]-'0');
        if(s[i+1] == 'u')continue;
        int nx = s[i+1] - '0';
        dp[state][nx] = true;
        if(state & (1<<nx)){
            cout << "UNSAFE" << endl;
            return;
        }
    }
    for(int i = 0; i < 1024; i++){
        for(int j = 0; j < 10; j++){
            if(!dp[i][j])continue;
            for(int k = 0; k < 1024; k++){
                if(i&k)continue;
                for(int l = 0; l < 10; l++){
                    if(!dp[k][l])continue;
                    bool f = i & (1<<l);
                    bool g = k & (1<<j);
                    if(f and g){
                        cout << "UNSAFE" << endl;
                        return;
                    }
                    else if(f){
                        dp[i|k][j] = true;
                    }
                    else if(g){
                        dp[i|k][l] = true;
                    }
                }
            }
        }
    }
    cout << "SAFE" << endl;
    return;
}
int main(){
    int n;
    while(cin >> n and n > 0){
        solve(n);
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3400
final_rank: 1

code_snippet: #include <bits/stdc++.h>
#define fi first
#define se second
#define rep(i,s,n) for (int i = (s); i < (n); ++i)
#define rrep(i,n,g) for (int i = (n)-1; i >= (g); --i)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define len(x) (int)(x).size()
#define dup(x,y) (((x)+(y)-1)/(y))
#define pb push_back
#define eb emplace_back
#define Field(T) vector<vector<T>>
using namespace std;
using ll = long long;
using ull = unsigned long long;
template<typename T> using pq = priority_queue<T,vector<T>,greater<T>>;
using P = pair<int,int>;
template<class T>bool chmax(T&a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T>bool chmin(T&a,T b){if(b<a){a=b;return 1;}return 0;}

bool solve() {
  int n;
  cin >> n;
  if (n == 0) {
    return 1;
  }
  string s;
  cin >> s;
  int m = 10;
  vector<int> f(1<<m);
  int idx = 0;
  rep(i,0,n) {
    if (s[i] == 'u') {
      int b = 0;
      rep(j,idx,i) {
        if ((b >> (s[j]-'0'))&1) {
          cout << "UNSAFE" << endl;
          return 0;
        }
        f[b] |= (1<<(s[j]-'0'));
        b |= (1<<(s[j]-'0'));
      }
      idx = i+1;
    }
  }
  rep(t,0,1<<m) {
    if (__builtin_popcount(t) <= 1) continue; 
    vector<int> dp(1<<m, -1);
    function<bool(int)> rec = [&](int bit) {
      if (dp[bit] != -1) return dp[bit];
      if (bit != 0 && bit != t && (f[bit]&t)) {
        return dp[bit] = 1;
      } else if (__builtin_popcount(bit) == 1) {
        return dp[bit] = 0;
      }
      for (int nbit = bit&(bit-1); nbit > 0; nbit = bit&(nbit-1)) {
        if (rec(nbit) && rec(bit-nbit)) {
          return dp[bit] = 1;
        }
      }
      return dp[bit] = 0;
    };
    if (rec(t)) {
      cout << "UNSAFE" << endl;
      return 0;
    }
  }
  cout << "SAFE" << endl;
  return 0;
}

int main() {
  while(!solve());
  return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 3380
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef int ll;
typedef unsigned long long ull;
typedef long double ld;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define rrep(i,start,end) for (ll i = start;i >= (ll)(end);i--)
#define repn(i,end) for(ll i = 0; i <= (ll)(end); i++)
#define reps(i,start,end) for(ll i = start; i < (ll)(end); i++)
#define repsn(i,start,end) for(ll i = start; i <= (ll)(end); i++)
#define each(p,a) for(auto &p:a)
typedef vector<ll> vll;
typedef vector<pair<ll ,ll>> vpll;
typedef vector<vector<ll>> vvll;
typedef set<ll> sll;
typedef map<ll , ll> mpll;
typedef pair<ll ,ll> pll;
typedef tuple<ll , ll , ll> tpl3;
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define Str(...) string __VA_ARGS__; input(__VA_ARGS__)
#define Ch(...) char __VA_ARGS__; input(__VA_ARGS__)
#define all(a)  (a).begin(),(a).end()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
#define sz(x) (ll)x.size()
// << std::fixed << std::setprecision(10)
const ll INF = 1LL << 30;
const ld EPS = 1e-9;
 
ll lceil(ll a,ll b){if(a%b==0){return a/b;}if(a>=0){return (a/b)+1;}else{return -((-a)/b);}}
ll lfloor(ll a,ll b){if(a%b==0){return a/b;}if(a>=0){return (a/b);}else{return -((-a)/b)-1;}}
inline ll positive_mod(ll a,ll m){return (a % m + m)%m;}
inline ll popcnt(ull a){ return __builtin_popcountll(a);}
//0indexed
inline ll topbit(ll a){assert(a != 0);return 63 - __builtin_clzll(a);}
inline ll smlbit(ll a){assert(a != 0);return __builtin_ctzll(a);}
template<class T> bool chmin(T& a, T b){if(a > b){a = b;return true;}return false;}
template<class T> bool chmax(T& a, T b){if(a < b){a = b;return true;}return false;}
template<typename T> std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
template<typename T> std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
template<typename T1, typename T2>std::ostream &operator<< (std::ostream &os, std::pair<T1,T2> p){os << "{" << p.first << "," << p.second << "}";return os;}
template<class... T>void input(T&... a){(cin >> ... >> a);}
void print(){cout << endl;}
template<class T, class... Ts>void print(const T& a, const Ts&... b){cout << a;((cout << ' ' << b), ...);cout << endl;}
template<class T> void pspace(const T& a){ cout << a << ' ';}
void perr(){cerr << endl;}
template<class T, class... Ts>void perr(const T& a, const Ts&... b){cerr << a;((cerr << ' ' << b), ...);cerr << endl;}
void yes(bool i = true){ return print(i?"yes":"no"); }
void Yes(bool i = true){ return print(i?"Yes":"No"); }
void YES(bool i = true){ return print(i?"YES":"NO"); }
template <class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v) e++;return v;}
template <class T> vector<T> operator++(vector<T> &v, signed) {auto res = v;for(auto &e : v) e++;return res;}
template <class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v) e--;return v;}
template <class T> vector<T> operator--(vector<T> &v, signed) {auto res = v;for(auto &e : v) e--;return res;}
//grid探索用
vector<ll> _ta = {0,0,1,-1,1,1,-1,-1};
vector<ll> _yo = {1,-1,0,0,1,-1,1,-1};
bool isin(ll now_i,ll now_j,ll h,ll w){return (0<=now_i && now_i < h && 0 <= now_j && now_j < w);}
  
ll lpow(ll x,ll n){ll ans = 1;while(n >0){if(n & 1)ans *= x;x *= x;n >>= 1;}return ans;}
ll Modlpow(ll x,ll n,ll m){ll ans = 1;ll a = x%m;while(n >0){if(n & 1){ans *= a;ans%= m;}a *= a;a %= m;n >>= 1;}return ans;} 
const ll MOD9 = 998244353LL;
const ll MOD10 = 1000000007LL;
 
void solve(ll n){
  Str(s);
  vector<vector<ll>> gru;
  gru.push_back({});
  rep(i,n){
    if(isdigit(s[i])){
      gru.back().push_back(s[i]-'0');
    }else{
      gru.push_back({});
    }
  }
  vector<vector<ll>> tmpgru;
  rep(i,sz(gru)){
    if(sz(gru[i]) > 0)tmpgru.push_back(gru[i]);
  }
  swap(gru,tmpgru);
  ll siz= sz(gru);
  if(siz == 0){
    cout << "SAFE" << endl;
    return;
  } 
  vector<unordered_set<ll>> dp(vector<unordered_set<ll>>(1<<10));
  dp[0].insert(0);
  rep(i,siz){
    vector<unordered_set<ll>> ndp(vector<unordered_set<ll>>(1<<10));
    rep(j,1 << 10){
      each(k,dp[j]){//使われてないやつ
        //選ばない
        if(j >> gru[i][0] & 1){
          ndp[j].insert(k);
        }else{
          ndp[j].insert(k|1<<gru[i][0]);
        }
        ll nj = j;
        ll nk = k;
        rep(l,sz(gru[i])-1){
          if(nj >> gru[i][l] & 1){
            break;//すでに取られてるから取れない
          }
          //置く
          nj |= 1 << gru[i][l];
          if(nk >> gru[i][l]&1){
            nk ^= 1 << gru[i][l];
          }
          if(nj >> gru[i][l+1] & 1){
            ndp[nj].insert(nk);
          }else{
            ndp[nj].insert(nk|1<< gru[i][l+1]);
          }
        }
      }
    }
    swap(dp,ndp);
  }
  rep(j,1 << 10){
    if(dp[j].contains(0)){
      cout << "UNSAFE" << endl;
      return ;
    }
  }
  
  cout << "SAFE" << endl;
}

int main(){
  ios::sync_with_stdio(false);cin.tie(nullptr);
  while(true){
    LL(n);
    if(n == 0)break;
    solve(n);
  }
}
accuracy: 1
time_ms: 3320
memory_kb: 4420
final_rank: 16

code_snippet: #include <bits/stdc++.h>
#include <unordered_map>
#include <stdlib.h>
using namespace std;
#define rep(i, a, n) for(ll i = a; i < n; i++)
#define rrep(i, a, n) for(ll i = a; i >= n; i--)
#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(x) (x).begin(), (x).end()
//constexpr ll MOD = 1000000007;
constexpr ll MOD = 998244353;
constexpr int IINF = 1001001001;
constexpr ll INF = 1LL<<60;
template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(b<a)a=b;}

ll gcd(ll a, ll b){
    if(a%b == 0){
      return b;
    }else{
      return gcd(b, a%b);
    }
}

ll lcm(ll a, ll b){
    return a*b / gcd(a, b);
}

ll powMod(ll x, ll n) {
    if (n == 0) return 1 % MOD;
    ll val = powMod(x, n / 2);
    val *= val;
    val %= MOD;
    if (n % 2 == 1) val *= x;
    return val % MOD;
}

int main() {
    while(true){
        ll n; cin >> n;
        if(n == 0) break;
        string s; cin >> s;
        vector<pll> pairs;
        {
            ll l = 0;
            ll f = 1;
            while(l < n){
                ll r = l+1;
                if(s[l] == 'u'){
                    l++;
                    continue;
                }
                while(r < n && s[r] != 'u') r++;
                // cout << l << " " << r << endl;
                ll num = 0;
                rep(i,l,r-1){
                    num ^= (1<<(s[i]-'0'));
                    pairs.push_back({num, s[i+1]-'0'});
                    if(num >> (s[i+1]-'0') & 1){
                        f = 0;
                        break;
                    }
                }
                l = r+1;
            } 
            if(f == 0){
                cout << "UNSAFE" << endl;
                continue;
            }
        }
        vector<vector<ll>> dp(1<<10, vector<ll>(10,0));
        for(auto [x, y] : pairs) dp[x][y] = 1;
        ll f = 1;
        rep(i,0,1<<10)rep(j,0,10){
            if(dp[i][j] == 0) continue;
            for(auto [x,y]: pairs){
                if((x&i) == 0 && (i>>y&1) == 1)  dp[i|x][j] = 1;
                if((x&i) == 0 && (x>>j&1) == 1)  dp[i|x][y] = 1;
            } 
        }
        rep(i,0,1<<10)rep(j,0,10){
            if(dp[i][j] == 0) continue;
            rep(k,i+1,1<<10)rep(l,0,10){
                if(dp[k][l] == 1 && (i&k) == 0 && (k>>j&1) && (i>>l&1)) f = 0;
            }
        }
        if(f == 0) cout << "UNSAFE" << endl;
        else cout << "SAFE" << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 860
memory_kb: 3840
final_rank: 10

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double x) {
    wt_real(x);
}

template <class T, class U> void wt(const pair<T, U> val) {
    wt(val.first);
    wt(' ');
    wt(val.second);
}
template <size_t N = 0, typename T> void wt_tuple(const T t) {
    if constexpr (N < std::tuple_size<T>::value) {
        if constexpr (N > 0) {
            wt(' ');
        }
        const auto x = std::get<N>(t);
        wt(x);
        wt_tuple<N + 1>(t);
    }
}
template <class... T> void wt(tuple<T...> tpl) {
    wt_tuple(tpl);
}
template <class T, size_t S> void wt(const array<T, S> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}
template <class T> void wt(const vector<T> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}

void print() {
    wt('\n');
}
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    wt(head);
    if (sizeof...(Tail))
        wt(' ');
    print(forward<Tail>(tail)...);
}
void __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

template <unsigned mod = 1000000007> struct fp {
    unsigned v;
    static constexpr int get_mod() {
        return mod;
    }
    constexpr unsigned inv() const {
        assert(v != 0);
        int x = v, y = mod, p = 1, q = 0, t = 0, tmp = 0;
        while (y > 0) {
            t = x / y;
            x -= t * y, p -= t * q;
            tmp = x, x = y, y = tmp;
            tmp = p, p = q, q = tmp;
        }
        if (p < 0)
            p += mod;
        return p;
    }
    constexpr fp(ll x = 0) : v(x >= 0 ? x % mod : (mod - (-x) % mod) % mod) {}
    fp operator-() const {
        return fp() - *this;
    }
    fp pow(ull t) {
        fp res = 1, b = *this;
        while (t) {
            if (t & 1)
                res *= b;
            b *= b;
            t >>= 1;
        }
        return res;
    }
    fp &operator+=(const fp &x) {
        if ((v += x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator-=(const fp &x) {
        if ((v += mod - x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator*=(const fp &x) {
        v = ull(v) * x.v % mod;
        return *this;
    }
    fp &operator/=(const fp &x) {
        v = ull(v) * x.inv() % mod;
        return *this;
    }
    fp operator+(const fp &x) const {
        return fp(*this) += x;
    }
    fp operator-(const fp &x) const {
        return fp(*this) -= x;
    }
    fp operator*(const fp &x) const {
        return fp(*this) *= x;
    }
    fp operator/(const fp &x) const {
        return fp(*this) /= x;
    }
    bool operator==(const fp &x) const {
        return v == x.v;
    }
    bool operator!=(const fp &x) const {
        return v != x.v;
    }
    friend istream &operator>>(istream &is, fp &x) {
        return is >> x.v;
    }
    friend ostream &operator<<(ostream &os, const fp &x) {
        return os << x.v;
    }
};

template <unsigned mod> void rd(fp<mod> &x) {
    fastio::rd(x.v);
}
template <unsigned mod> void wt(fp<mod> x) {
    fastio::wt(x.v);
}

template <typename T> T Inv(ll n) {
    static const int md = T::get_mod();
    static vector<T> buf({0, 1});
    assert(n > 0);
    n %= md;
    while (SZ(buf) <= n) {
        int k = SZ(buf), q = (md + k - 1) / k;
        buf.push_back(buf[k * q - md] * q);
    }
    return buf[n];
}

template <typename T> T Fact(ll n, bool inv = 0) {
    static const int md = T::get_mod();
    static vector<T> buf({1, 1}), ibuf({1, 1});
    assert(n >= 0 and n < md);
    while (SZ(buf) <= n) {
        buf.push_back(buf.back() * SZ(buf));
        ibuf.push_back(ibuf.back() * Inv<T>(SZ(ibuf)));
    }
    return inv ? ibuf[n] : buf[n];
}

template <typename T> T nPr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nCr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(r, inv ^ 1) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nHr(int n, int r, bool inv = 0) {
    return nCr<T>(n + r - 1, r, inv);
}

/**
 * @brief Modint
 */

int main() {
while(1) {
    int N;
    cin >> N;
    if (N == 0) return 0;
    string S;
    cin >> S;
    bool memo[1024][10] = {};
    int Cur = 0;
    bool ANS = false;
    rep(i,0,N) {
        if (S[i] == 'u') Cur = 0;
        else {
            int Next = S[i] - '0';
            if ((Cur >> Next) & 1) {
                ANS = true;
            }
            memo[Cur][Next] = true;
            Cur |= (1<<Next);
        }
    }
    if (ANS) {
        cout << "UNSAFE" << endl;
        continue;
    }
    queue<pair<int,int>> Q;
    rep(i,0,1<<10) {
        rep(j,0,10) {
            if (memo[i][j]) Q.push({i,j});
        }
    }
    while(!Q.empty()) {
        pair<int,int> P = Q.front();
        Q.pop();
        int Comp = 1023-P.first;
        for (int NX = Comp; NX >= 0; NX--) {
            NX &= Comp;
            for (int NY = 0; NY < 10; NY++) {
                if (memo[NX][NY]) {
                    if ((P.first >> NY) & 1 && !memo[P.first | NX][P.second]) {
                        memo[P.first | NX][P.second] = true;
                        Q.push({P.first | NX, P.second});
                    }
                    if ((NX >> P.second) & 1 && !memo[P.first | NX][NY]) {
                        memo[P.first | NX][NY] = true;
                        Q.push({P.first | NX, NY});
                    }
                }
            }
        }
    }
    rep(LX,0,1024) {
        int Comp = 1023 - LX;
        for (int RX = Comp; RX >= 0; RX--) {
            RX &= Comp;
            rep(LY,0,10) {
                rep(RY,0,10) {
                    if (memo[LX][LY] && memo[RX][RY] && (LX >> RY) & 1 && (RX >> LY) & 1) ANS = true;
                }
            }
        }
    }
    cout << (ANS ? "UNSAFE" : "SAFE") << endl;
}
}
accuracy: 1
time_ms: 270
memory_kb: 3556
final_rank: 6

code_snippet: #include<bits/stdc++.h>
// #include<atcoder/all>
// #include<boost/multiprecision/cpp_int.hpp>

using namespace std;
// using namespace atcoder;
// using bint = boost::multiprecision::cpp_int;
using ll = long long;
using ull = unsigned long long;
using P = pair<ll,ll>;
using vi = vector<ll>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
#define rep(i,n) for(ll i = 0;i < (ll)n;i++)
#define ALL(x) (x).begin(),(x).end()
#define sz(c) ((ll)(c).size())
#define LB(A,x) (int)(lower_bound(A.begin(),A.end(),x)-A.begin())
#define UB(A,x) (int)(upper_bound(A.begin(),A.end(),x)-A.begin())
// #define MOD 1000000007
#define MOD 998244353
template<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){for(int i = 0;i < v.size();i++)os<<v[i]<<(i+1!=v.size()?" ":"");return os;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}
template<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.first<<" "<<p.second;return os;}
template<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.first>>p.second;return is;}


int main(){
  
  ios_base::sync_with_stdio(0), cin.tie(0);
  while(1){
    int n;cin >> n;
    if(!n)break;
    string s;cin >> s;
    int msk = 0;
    vector<vector<bool>> dp(1 << 10,vector<bool>(10,false));
    bool res = true;
    rep(i,n-1){
      if(s[i] == 'u')msk = 0;
      else{
        if(msk & (1 << (s[i]-'0'))){
          res = false;
        }else{
          if(msk){
            dp[msk][s[i]-'0'] = true;
          }
          msk |= (1 << (s[i]-'0'));
        }
      }
    }
    for(int bit = 1;bit < 1 << 10;bit++){
      rep(i,10)rep(j,10){
        int S = bit;
        while(S){
          int T = bit - S;
          if((T & (1 << i)) && dp[S][i] && dp[T][j]){
            if((S & (1 << j)))res = false;
            dp[bit][j] = true;
          }
          S = (S-1) & bit;
        }
      }
    }
    cout << (res ? "SAFE\n" : "UNSAFE\n");
  }


  return 0;
}
accuracy: 1
time_ms: 210
memory_kb: 3472
final_rank: 3

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

using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vd = vector<double>;
using vvd = vector<vd>;
using vvvd = vector<vvd>;
#define all(A) A.begin(),A.end()
#define ALL(A) A.begin(),A.end()
#define rep(i, n) for (int i = 0; i < (int) (n); i++)
template<class T>
bool chmax(T& p, T q) {
    if (p < q) {
        p = q; return 1;
    }
    return 0;
};


void solve(ll N) {
    string S;
    cin >> S;

    ll p = 0;
    vector<set<ll>> DP(1024);
    rep(i, S.size()) {
        if (S[i] == 'u') {
            p = 0;
        }
        else {
            ll d = S[i] - '0';
            DP[p].insert(d);
            if (p & (1 << d)) {
                cout << "UNSAFE" << endl;
                return;
            }
            p += (1 << d);
        }
    }
    rep(bit, 1024) {
        for (ll b = bit; b >= 0; b = (b - 1) & (bit)) {
            ll a = bit - b;
            for (auto d : DP[a]) {
                if (b & (1 << d)) {
                    for (auto e : DP[b]) {
                        if (bit == 1 && e == 0) {
                            cout << "";
                        }
                        DP[bit].insert(e);
                    }
                }
            }
            if (b == 0)break;
        }

    }
    rep(bit, 1024) {
        for (ll b = bit; b >= 0; b = (b - 1) & (bit)) {
            ll a = bit - b;
            for (auto d : DP[a])for (auto e : DP[b]) {
                if (b & (1 << d))
                {
                    if (a & (1 << e)) {
                        cout << "UNSAFE" << endl;
                        return;
                    }
                }
                
            }
            if (b == 0)break;
        }
    }
    cout << "SAFE" << endl;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);


    ll N;
    while (cin >> N) {
        if (N == 0)return 0;
        solve(N);
    }

}
accuracy: 1
time_ms: 170
memory_kb: 3712
final_rank: 5

code_snippet: #include <bits/stdc++.h>

bool solve() {
    int N;
    std::cin >> N;
    if (N == 0) return false;
    std::string S;
    std::cin >> S;
    std::vector<std::pair<int, int>> state(S.size());
    bool ans{};
    {
        int cur{};
        for (int i{} ; i + 1 < (int)S.size() ; i++) {
            if (S[i] == 'u') cur = 0;    
            else {
                if (cur & (1 << (S[i] - '0'))) {
                    ans = true;
                }
                cur |= (1 << (S[i] - '0'));
            }

            if (S[i + 1] == 'u') state[i] = { -1, -1 };
            else if (cur == 0) state[i] = { -1, -1 };
            else state[i] = { cur, S[i + 1] - '0' };
        }
    }
    std::vector<std::vector<int>> T(1 << 10);
    for (int i{} ; i < (int)S.size() ; i++) {
        if (state[i].first != -1) {
            T[state[i].first].push_back(i);
        }
    }
    std::vector vis(1 << 10, std::vector<bool>(S.size()));
    auto dfs{[&](auto dfs, int cur, int v) -> void {
        assert(state[v].first != -1);
        if (ans) return;
        vis[cur][v] = true;
        if (cur & (1 << state[v].second)) {
            ans = true;
            return;
        }
        int mask{((1 << 10) - 1) ^ cur};
        for (int bit{mask} ; ; bit = (bit - 1) & mask) {
            for (auto x : T[bit]) {
                if (state[x].first & (1 << state[v].second)) {
                    assert((cur & state[x].first) == 0);
                    int nextcur{cur | state[x].first};
                    if (vis[nextcur][x]) continue;
                    dfs(dfs, nextcur, x);
                }
            }
            if (bit == 0) break;
        }
    }};
    for (int i{} ; i < (int)S.size() ; i++) {
        if (state[i].first != -1) dfs(dfs, state[i].first, i);
    }
    std::cout << (ans ? "UNSAFE" : "SAFE") << '\n';
    return true;
}

int main() {
    std::cin.tie(nullptr)->sync_with_stdio(false);
    while (solve()) ;
}
accuracy: 1
time_ms: 370
memory_kb: 4520
final_rank: 9

code_snippet: #include <bits/stdc++.h>

int solve() {
    int n;
    std::cin >> n;
    if (n == 0) return 1;
    std::string s;
    std::cin >> s;

    std::vector<std::pair<unsigned, int>> ts;
    for (int l = 0, r = 0; l < n; l = r) {
        while (l < n && s[l] == 'u') l++;
        if (l == n) break;
        r = l;
        while (r < n && s[r] != 'u') r++;
        unsigned state = 0;
        for (int i = l; i < r; i++) {
            int last = s[i] - '0';
            ts.emplace_back(state, last);
            state |= 1 << (int)(s[i] - '0');
        }
    }

    std::set<std::pair<unsigned, int>> memo;
    auto dfs = [&](auto self, unsigned state, int i) -> bool {
        std::pair<unsigned, int> key = {state, i};
        if (memo.find(key) != memo.end()) return false;
        memo.insert(key);
        if (state & (1 << i)) return true;
        for (auto [mask, j]: ts) {
            if ((state & mask) != 0) continue;
            if (mask & (1 << i)) {
                if (self(self, state | mask, j)) return true;
            }
        }
        return false;
    };
    for (auto [state, last]: ts) {
        if (dfs(dfs, state, last)) {
            std::cout << "UNSAFE" << '\n';
            return 0;
        }
    }
    std::cout << "SAFE" << '\n';
    return 0;
}

int main() {
    while (!solve());
}
accuracy: 1
time_ms: 390
memory_kb: 3616
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define ALL(v) v.begin(),v.end()
#define dbg(x) cerr << #x << ": " << (x) << endl;
template<class F, class S>
ostream& operator<<(ostream& os, pair<F,S>& p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template<class Iter>
void print(Iter beg, Iter end) {
    for (Iter itr = beg; itr != end; ++itr) {
        cerr << *itr << ' ';
    }
    cerr << '\n';
}

bool solve() {
    int n;
    string s;
    cin >> n;
    if (n == 0) exit(0);
    cin >> s;
    for (int i = 0; i < n; ++i) if (s[i] != 'u') s[i] -= '0';

    int K = 10;
    int have = 0;
    vector dp(1<<K, vector(K, false));
    for (int i = 0; i < n; ++i) {
        if (have >> s[i] & 1) {
            return false;
        }
        dp[have][s[i]] = 1;
        if (s[i] == 'u') {
            have = 0;
        } else {
            have |= 1 << s[i];
        }
    }
    for (int a = 0; a < 1<<K; ++a) {
        for (int b = 0; b < K; ++b) {
            if (!dp[a][b]) continue;
            for (int c = 0; c < 1<<K; ++c) {
                for (int d = 0; d < K; ++d) {
                    if (!dp[c][d]) continue;
                    if (a & c) continue;

                    if ((a >> d & 1) && (c >> b & 1)) {
                        return false;
                    }

                    if (a >> d & 1) dp[a | c][b] = 1;
                    if (c >> b & 1) dp[a | c][d] = 1;
                }
            }
        }
    }
    return true;
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    while (true) {
        cout << (solve() ? "SAFE" : "UNSAFE") << '\n';
    }
}
accuracy: 1
time_ms: 310
memory_kb: 3356
final_rank: 4

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

using ll = long long;

bool is_end = false;

bitset<(1<<10)> dp;

void calc()
{
    ll N; cin >> N;
    
    if (N == 0)
    {
        is_end = true;
        return;
    }
    
    string S; cin >> S;
    
    const uint siz = (1<<10);
    vector< bitset<siz> > locked(10);
    
    uint hoge = 0;
    for (int i = 0; i < N; ++i)
    {
        char c = S[i];
        
        if (c == 'u')
        {
            hoge = 0;
        }
        else
        {
            int n = c - '0';
            locked[n].set(hoge);
            hoge |= (1u<<n);
        }
    }
    
    bitset<siz> dp(0);
    bool safe = true;
    for (uint bit = 0; bit < siz; ++bit)
    {
        dp = 0;
        for (int i = 0; i < 10; ++i)
        {
            if (bit & (1<<i)) dp |= locked[i];
        }
        
        for (uint inbit = 0; inbit < siz; ++inbit)
        {
            if (dp[inbit]) continue;
            for (uint subbit = inbit; subbit > inbit / 2; subbit = inbit & (subbit - 1))
            {
                if (dp[subbit] && dp[inbit ^ subbit])
                {
                    dp[inbit] = 1;
                    break;
                }
            }
        }
        
        for (uint inbit = 0; inbit < siz; ++inbit)
        {
            if ((bit & inbit) == bit)
            {
                if (dp[inbit])
                {
                    safe = false;
                    break;
                }
            }
        }
        
        if (!safe) break;
    }
    
    
    cout << (safe ? "SAFE" : "UNSAFE") << endl;
    
    return;
}

int main()
{
    while (!is_end)
    {
        calc();
    }
    
    return 0;
}
accuracy: 1
time_ms: 1150
memory_kb: 3372
final_rank: 12

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

using ll = long long;

bool is_end = false;

bitset<(1<<10)> dp;

void calc()
{
    ll N; cin >> N;
    
    if (N == 0)
    {
        is_end = true;
        return;
    }
    
    string S; cin >> S;
    
    const ll siz = (1<<10);
    vector< bitset<siz> > locked(10);
    
    ll hoge = 0;
    for (int i = 0; i < N; ++i)
    {
        char c = S[i];
        
        if (c == 'u')
        {
            hoge = 0;
        }
        else
        {
            int n = c - '0';
            locked[n].set(hoge);
            hoge |= (1LL<<n);
        }
    }
    
    bitset<siz> dp(0);
    bool safe = true;
    for (int bit = 0; bit < siz; ++bit)
    {
        dp = 0;
        for (int i = 0; i < 10; ++i)
        {
            if (bit & (1<<i)) dp |= locked[i];
        }
        
        for (int inbit = 0; inbit < siz; ++inbit)
        {
            if (dp[inbit]) continue;
            for (int subbit = inbit; subbit > 0; subbit = inbit & (subbit - 1))
            {
                if (dp[subbit] && dp[inbit ^ subbit]) dp[inbit] = 1;
            }
        }
        
        for (int inbit = 0; inbit < siz; ++inbit)
        {
            if ((bit & inbit) == bit)
            {
                if (dp[inbit]) safe = false;
            }
        }
        
        if (!safe) break;
    }
    
    
    cout << (safe ? "SAFE" : "UNSAFE") << endl;
    
    return;
}

int main()
{
    while (!is_end)
    {
        calc();
    }
    
    return 0;
}
accuracy: 1
time_ms: 3160
memory_kb: 3344
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define ALL(v) v.begin(),v.end()
#define dbg(x) cerr << #x << ": " << (x) << endl;
template<class F, class S>
ostream& operator<<(ostream& os, pair<F,S>& p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template<class Iter>
void print(Iter beg, Iter end) {
    for (Iter itr = beg; itr != end; ++itr) {
        cerr << *itr << ' ';
    }
    cerr << '\n';
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    while (true) {
        int n;
        string s;
        cin >> n;
        if (n == 0) break;
        cin >> s;

        bool safe = true;
        int K = 10;
        vector dp(1<<K, vector(K, false));
        int mask = 0;
        for (int i = 0; i < n; ++i) {
            if (s[i] == 'u') {
                mask = 0;
            } else {
                s[i] -= '0';
                dp[mask][s[i]] = true;
                if (mask & 1<<s[i]) {
                    safe = false;
                    break;
                } else {
                    mask |= 1 << s[i];
                }
            }
        }
        for (int a = 0; a < 1<<K; ++a) {
            for (int b = 0; b < K; ++b) {
                for (int c = 0; c < 1<<K; ++c) {
                    for (int d = 0; d < K; ++d) {
                        if (dp[a][b] && dp[c][d] && (a & c)==0 && (c & (1 << b))) {
                            dp[a | c][d] = true;
                        }
                        if (dp[a][b] && dp[c][d] && (a & c)==0 && (a & (1 << d))) {
                            dp[a | c][b] = true;
                        }
                    }
                }
            }
        }
        if (safe) {
            vector<pair<int,int>> state;
            for (int i = 0; i < 1<<K; ++i) {
                for (int j = 0; j < K; ++j) {
                    if (dp[i][j]) state.emplace_back(i, j);
                }
            }
            for (auto [a,b] : state) {
                for (auto [c,d] : state) {
                    if (a & c) continue;
                    if ((a & (1 << d)) && (c & (1 << b))) {
                        safe = false;
                        break;
                    }
                }
            }
        }
        cout << (safe ? "SAFE" : "UNSAFE") << '\n';
    }
}
accuracy: 1
time_ms: 3860
memory_kb: 3596
final_rank: 17

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,s,t) for (int i = (int)(s); i < (int)(t); ++i)
#define all(x) (x).begin(), (x).end()

template<typename T>
void print(vector<T>& vs){
    for(auto x:vs)cout<<x<<" ";
    cout<<endl;
}

bool dp[1<<10][1<<10];

int main() {
    while(true){
        int n;
        cin>>n;
        if(n==0)break;
        string s;
        cin>>s;

        // S -> k
        // take S disjointly. if all k are in S then deadlock

        // dp[S][T]: locked S, next T

        vector<vector<int>> G(1<<10);
        int S=0;
        rep(i,0,n){
            if(s[i]!='u'){
                G[S].push_back(s[i] - '0');
                S|=(1<<(s[i]-'0'));
            }else{
                S=0;
            }
        }
        rep(S,0,1<<10){
            sort(all(G[S]));
            G[S].erase(unique(all(G[S])), G[S].end());
        }

        memset(dp, 0, sizeof(dp));

        dp[0][0]=1;
        rep(S,0,1<<10){
            int X=S;
            do{
                for(int k:G[X]){
                    rep(T,0,1<<10){
                        dp[S][T|(1<<k)] = dp[S][T|(1<<k)] || dp[S^X][T];
                    }
                }
                X=(X-1)&S;
            }while(X!=S);
        }
        bool deadlock =false;
        rep(S,0,1<<10){
            rep(T,1,1<<10){
                if(dp[S][T] && ((S&T)==T)){
                    deadlock=true;
                    break;
                }
            }
            if(deadlock)break;
        }
        cout<<(deadlock?"UNSAFE":"SAFE")<<endl;
    }
}
accuracy: 1
time_ms: 2370
memory_kb: 4596
final_rank: 14

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vb = vector<bool>;
using vvb = vector<vb>;
using vvvb = vector<vvb>;
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(A) A.begin(),A.end()

int main() {

    ll N;
    while (cin >> N) {
        if (N == 0)return 0; string S;
        cin >> S;
        vvll OK(1024, vll(1024, 0));
        rep(bit, 1024) {
            ll dit = 0;
            bool say=0;
            rep(i, N) {
                if (S[i] == 'u') {
                    dit = 0;
                    say=0;
                }
                else if(!say){
                    ll d = S[i] - '0';
                    OK[bit][dit] |= (1 << d);
                    if ((bit | dit) & (1 << d)){
                        say=1;
                    }
                    dit += (1 << d);
                }
            }
        }
        vvb DP(1024, vb(1024, 0));
        rep(i, 1024)rep(k, 10)if (OK[0][i] & (1 << k))DP[i][1 << k] = 1;
        string AN = "SAFE";
        rep(bit, 1024) {
            rep(kit, 1024) {
                if (DP[bit][kit]) {
                    if ((bit & kit) == kit) {
                        AN = "UN" + AN;
                        break;
                    }
                    else {
                        ll zit = 1023 - bit;
                        for (ll b = zit; b >= 0; b = (b - 1) & zit) {
                            if (b == 1) {
                                cout << "";
                            }
                            rep(k, 10) {
                                if (OK[bit][b] & (1 << k)) {
                                    DP[bit|b][kit | (1 << k)] = 1;
                                }
                            }
                            if (b == 0)break;
                        }
                    }
                }
            }
            if (AN[0] == 'U')break;
        }
        cout << AN << endl;
    }
}
accuracy: 1
time_ms: 2990
memory_kb: 11780
final_rank: 20

code_snippet: #include<iostream>
#include<vector>
using namespace std;
vector<int>G[1<<10];
bool dp[1<<10][1<<10];
string S;
int main()
{
	int N;
	while(cin>>N,N)
	{
		cin>>S;
		for(int i=0;i<1<<10;i++)G[i].clear();
		bool out=false;
		for(int i=0;i<N;)
		{
			int j=i;
			while(S[j]!='u')j++;
			int ex=0;
			for(int k=i;k<j;k++)
			{
				int u=S[k]-'0';
				if(ex>>u&1)
				{
					out=true;
					break;
				}
				G[ex].push_back(u);
				ex|=1<<u;
			}
			i=j+1;
		}
		if(out)
		{
			cout<<"UNSAFE"<<endl;
			continue;
		}
		for(int i=0;i<1<<10;i++)for(int j=0;j<1<<10;j++)dp[i][j]=false;
		dp[0][0]=true;
		for(int i=0;!out&&i<1<<10;i++)
		{
			int r=(1<<10)-1^i;
			for(int j=r;!out&&j>=0;j--)
			{
				j&=r;
				int nj=j^r;
				if(!dp[i][nj])continue;
				for(int k=r;!out&&k>=0;k--)
				{
					k&=r;
					for(int w:G[k])
					{
						int ni=i|k;
						int nnj=(nj|1<<w)&~ni;
						if(nnj==0)
						{
							out=true;
							break;
						}
						dp[ni][nnj]=true;
					}
				}
			}
		}
		cout<<(!out?"SAFE":"UNSAFE")<<endl;
	}
}
accuracy: 1
time_ms: 460
memory_kb: 4752
final_rank: 11

code_snippet: #include <algorithm>
#include <cassert>
#include <climits>
#include <iostream>
#include <numeric>
#include <utility>
#include <vector>

using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define For(i, a, b) for (int i = int(a); i < int(b); ++i)
#define rep(i, n) For(i, 0, n)
#define sz(v) int(v.size())
#define fora(s, v) for (auto &s : v)
#define all(v) v.begin(), v.end()

template <class T>
using V = vector<T>;
template <class T>
using VV = V<V<T>>;

template <class T>
bool chmax(T &a, const T b) {
    return a < b ? a = b, 1 : 0;
}

int main() {
    while (true) {
        int n;
        cin >> n;
        if (n == 0) break;
        string s;
        cin >> s;

        bool ans = true;

        VV<bool> f(1 << 10, V<bool>(10, false));
        {
            int S = 0;
            rep(i, n) {
                if (s[i] == 'u') {
                    S = 0;
                } else {
                    int k = s[i] - '0';

                    if (S >> k & 1) ans = false;

                    f[S][k] = true;
                    S |= 1 << k;
                }
            }
        }

        rep(S, 1 << 10) rep(i, 10) {
            if (!f[S][i]) continue;
            rep(T, 1 << 10) rep(j, 10) {
                if (!f[T][j]) continue;

                auto c1 = ((S & T) == 0) && (T >> i & 1);
                auto c2 = ((S & T) == 0) && (S >> j & 1);
                if (c1 && c2) {
                    ans = false;
                }
                if (c1) {
                    f[S | T][j] = true;
                }
                if (c2) {
                    f[S | T][i] = true;
                }
            }
        }

        puts(ans ? "SAFE" : "UNSAFE");
    }
}
accuracy: 1
time_ms: 840
memory_kb: 3464
final_rank: 8

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<cassert>
using namespace std;
using ll = long long;
#define chmin(a,b) a = min(a,b)
int n;
void solve(){
    string s;
    cin>>s;
    int ni = 0;
    int now = 0;
    vector<vector<int>> can(10,vector<int>(1<<10,0));
    while(ni<n){
        if(s[ni]=='u'){
            now = 0;
            ni++;
            continue;
        }
        int nj = s[ni] - '0';
        now |= 1<<nj;
        if(s[ni+1]=='u') {
            ni++;
            continue;
        }
        int nk = s[ni+1] - '0';
        can[nk][now]=1;
        ni++;
    }
    vector<vector<int>> dp(1<<10,vector<int>(1<<10,1e9));
    dp[0][0] = 0;
    int mask = (1<<10) - 1;
    for(int i = 0;i<1<<10;i++){
        for(int j = 0;j<1<<10;j++){
            if(dp[i][j]>10) continue;
            int now = mask ^ j;
            for(int k = mask;k>=0;k--){
                k &= now;
                for(int l = 0;l<10;l++){
                    if(can[l][k]==0) continue;
                    chmin(dp[i|1<<l][j|k],dp[i][j]+1);
                }
            }
        }
    }
    for(int i = 1;i<1<<10;i++){
        for(int j = 0;j<1<<10;j++){
            if((i&j)!=i) continue;
            if(dp[i][j]<=10){
                cout<<"UNSAFE\n";
                return ;
            }
        }
    }
    cout<<"SAFE\n";
}
    
int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    while(true){
        cin>>n;
        if(n==0) break;
        solve();

    }
}
accuracy: 1
time_ms: 2790
memory_kb: 7284
final_rank: 19

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<cassert>
using namespace std;
using ll = long long;
#define chmin(a,b) a = min(a,b)
int n;
void solve(){
    string s;
    cin>>s;
    int ni = 0;
    int now = 0;
    vector<vector<int>> can(10,vector<int>(1<<10,0));
    while(ni<n){
        if(s[ni]=='u'){
            now = 0;
            ni++;
            continue;
        }
        int nj = s[ni] - '0';
        now |= 1<<nj;
        if(s[ni+1]=='u') {
            ni++;
            continue;
        }
        int nk = s[ni+1] - '0';
        can[nk][now]=1;
        ni++;
    }
    vector<vector<int>> dp(1<<10,vector<int>(1<<10,1e9));
    dp[0][0] = 0;
    int mask = (1<<10) - 1;
    for(int i = 0;i<1<<10;i++){
        for(int j = 0;j<1<<10;j++){
            if(dp[i][j]>10) continue;
            int now = mask ^ j;
            for(int k = mask;k>=0;k--){
                k &= now;
                for(int l = 0;l<10;l++){
                    if(can[l][k]==0) continue;
                    chmin(dp[i|1<<l][j|k],dp[i][j]+1);
                }
            }
        }
    }
    for(int i = 1;i<1<<10;i++){
        for(int j = 0;j<1<<10;j++){
            if((i&j)!=i) continue;
            if(dp[i][j]<=10){
                cout<<"UNSAFE\n";
                return ;
            }
        }
    }
    cout<<"SAFE\n";
}
    
int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    while(true){
        cin>>n;
        if(n==0) break;
        solve();

    }
}
accuracy: 1
time_ms: 2780
memory_kb: 7248
final_rank: 18

code_snippet: // (⁠◕⁠ᴗ⁠◕⁠✿⁠)

#include <bits/stdc++.h>
// #include <atcoder/all>
// using namespace atcoder;
// using mint = modint1000000007;
// using mint = modint998244353;
// using vmint = vc<mint>;using vvmint = vc<vmint>;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define srep(i, s, n) for (int i = s; i < n; i++)
#define drep(i, n) for (int i = n; i >= 0; i--)
#define dsrep(i, s, n) for (int i = s; i >= n; i--)
#define len(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define YES(n) cout << ((n) ? "YES" : "NO" ) << endl
#define Yes(n) cout << ((n) ? "Yes" : "No" ) << endl
using namespace std;
template<typename T> using vc = vector<T>;
template<typename T> using vv = vc<vc<T>>;
using vi = vc<int>;using vvi = vv<int>; using vvvi = vv<vi>;
using ll = long long;using vl = vc<ll>;using vvl = vv<ll>; using vvvl = vv<vl>;
using ld = long double; using vld = vc<ld>; using vvld = vc<vld>; using vvvld = vc<vvld>;
using uint = unsigned int;
using ull = unsigned long long;
const double pi = 3.141592653589793;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
// const int mod = 1000000007;
const int mod = 998244353;
inline bool inside(long long y, long long x, long long H, long long W) {return 0 <= y and y < H and 0 <= x and x < W; }

struct phash{
    inline size_t operator()(const pair<int,int> & p) const{
        const auto h1 = hash<int>()(p.first);
        const auto h2 = hash<int>()(p.second);
        return h1 ^ (h2 << 1);
    }
};

void solve(int &N){
    string S; cin >> S;
    vv<bool> possible((1 << 10), vc<bool>(10, false));
    ll now = 0;
    rep(i, N){
        if (S[i] == 'u') now = 0;
        else{
            if (now & (1 << (S[i] - '0'))){
                cout << "UNSAFE" << endl;
                return;
            }
            if (now != 0){
                possible[now][S[i] - '0'] = true;
            }
            now |= (1 << (S[i] - '0'));
        }
    }

    rep(a1, 1 << 10) rep(b1, 10) rep(a2, 1 << 10) rep(b2, 10){
        if (possible[a1][b1] && possible[a2][b2]){
            if ((a1 & a2) == 0 && (a1 >> b2) & 1 && (a2 >> b1) & 1){
                cout << "UNSAFE" << endl;
                return;
            }
            if ((a1 & a2) == 0 && (a1 >> b2) & 1){
                possible[a1 | a2][b1] = true;
            }
            if ((a1 & a2) == 0 && (a2 >> b1) & 1){
                possible[a1 | a2][b2] = true;
            }
        }
    }
    cout << "SAFE" << endl;
}

int main(){
    while (true){
        int N; cin >> N;
        if (N == 0) return 0;
        solve(N);
    }
}
accuracy: 1
time_ms: 1940
memory_kb: 3460
final_rank: 13