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 L0 to L9.
A digit k is the instruction for acquiring the lock Lk.
After one of the threads acquires a lock Lk,
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 Lk.

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 Lk is not kept by any thread,
the thread executes the instruction k and acquires Lk.

If the next instruction is a digit k and
the lock Lk 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 Sample Input

SAFE
UNSAFE
SAFE
UNSAFE
UNSAFE
UNSAFE

The second input "01u10u" may possibly cause a deadlock. After one
thread has executed the initial four instructions "01u1", the
thread keeps only one lock L1. If another thread executes the first
instruction '0' at this time, this thread acquires L0. Then, the
first thread tries to acquire L0, already kept by the second
thread, while the second thread tries to acquire L1, kept by the
first thread; This leads to a deadlock.

→
→

Figure 1: Why the Sample Input 2 "01u10u" is unsafe.

Contrarily, the third input "201u210u" is safe.
If one thread had executed up to "201u21" and another to "20", then
one may think it would lead to a deadlock, but this
can never happen because no two threads can simultaneously keep L2.

Solution in Rust (judge verdict: Accepted)

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::Read;
#[allow(dead_code)]
fn getline() -> String {
    let mut ret = String::new();
    std::io::stdin().read_line(&mut ret).ok().unwrap();
    ret
}
fn get_word() -> String {
    let mut stdin = std::io::stdin();
    let mut u8b: [u8; 1] = [0];
    loop {
        let mut buf: Vec<u8> = Vec::with_capacity(16);
        loop {
            let res = stdin.read(&mut u8b);
            if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {
                break;
            } else {
                buf.push(u8b[0]);
            }
        }
        if buf.len() >= 1 {
            let ret = String::from_utf8(buf).unwrap();
            return ret;
        }
    }
}

#[allow(dead_code)]
fn get<T: std::str::FromStr>() -> T { get_word().parse().ok().unwrap() }

fn solve() {
    loop {
        let n: usize = get();
        if n == 0 { break; }
        let s: Vec<_> = get_word().chars().collect();
        let mut set = vec![0; n + 1];
        let mut self_broken = false;
        for (i, ch) in s.into_iter().enumerate() {
            set[i + 1] = match ch {
                'u' => 0,
                x => {
                    let u = x as u8 - b'0';
                    if (set[i] & 1 << u) != 0 {
                        self_broken = true;
                        0
                    } else {
                        set[i] | 1 << u
                    }
                },
            }
        }
        if self_broken {
            println!("UNSAFE");
            continue;
        }
        let mut nxt_cand = [0; 1 << 10];
        for i in 1 .. n {
            if set[i] != 0 {
                nxt_cand[set[i - 1]] |= set[i] ^ set[i - 1];
            }
        }
        let mut ok = true;
        // TODO O(2^30) -> O(2^20)
        for bits in 1 .. 1 << 10 {
            let mut dp = vec![0; bits + 1];
            dp[0] = 1;
            let mut sub1iter = (bits - 1) & bits;
            loop {
                let sub1 = bits - sub1iter;
                let mut sub2 = sub1;
                loop {
                    if sub2 == 0 { break; }
                    if (nxt_cand[sub2] & bits) != 0 {
                        dp[sub1] |= dp[sub1 ^ sub2];
                    }
                    sub2 = (sub2 - 1) & sub1;
                }
                if sub1iter == 0 { break; }
                sub1iter = (sub1iter - 1) & bits;
            }
            if dp[bits] > 0 {
                ok = false;
                break;
            }
        }
        println!("{}", if ok { "SAFE" } else { "UNSAFE" });
    }
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}