### Saratov State University :: Online Contester

::Go
- home
- news
- register
 - update personal info
 - problemset archive
- submit
- status online
- standing
- contests
- virtual contests
- forum
- statistic
- FAQ
- projects

 ::Poll Are you registered on Codeforces?YesNoWhat is it???[results]

::webboard

 My Solution
Author: M.S.
ID: 004300
Problem: 502
Contest: 0
Date: 2011-08-15 13:56:00

My solution to this problem in C# .NET:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sgu502
{
class Program
{
static string digits = "0123456789";

static int[] to_int(string s)
{
int i, len = 0;
for (i = 0; i < s.Length; ++i)
if (digits.IndexOf(s[i]) >= 0) len++;
int[] result = new int[len];
for (i = len = 0; i < s.Length; ++i)
if (digits.IndexOf(s[i]) >= 0) result[len++] = (int)s[i] - (int)'0';
return result;
}
static int[] b_map = new int[10];
static bool permute(int step, int[] map, int[] res)
{
int i;
int[] t_map = new int[10];
int[] t_res = new int[res.Length];
for (i = 0; i < 10; ++i) t_map[i] = b_map[i];
int len = res.Length;
while (len > 0)
{
if (res[len - 1] == 0) --len; else break;
}
for (i = 0; i < len; ++i)
{
--t_map[res[i]];
}
for (i = 0; i < 10; ++i) if (t_map[i] != 0) break;
if (step == (res.Length - 4)) return false;
if (i == 10)
{
long l = 0, k = 1;
for (i = 0; i < res.Length; ++i, k *= 10) l += res[i] * k;
if (l != 0)
{
Console.WriteLine(l.ToString());
return true;
}
}

for (i = 0; i < 10; ++i)
{
int j = 0, k = i * 17;
for (j = 0; j < 10; ++j) t_map[j] = map[j];
for (j = 0; j < res.Length; ++j) t_res[j] = res[j];
int t = step, c = k;
while (c > 0)
{
int b = c;
res[t] += b;
c = res[t] / 10;
res[t] %= 10;
t++;
}

if (map[res[step]] > 0)
{
--map[res[step]];
if (permute(step + 1, map, res)) return true;
}

for (j = 0; j < 10; ++j) map[j] = t_map[j];
for (j = 0; j < res.Length; ++j) res[j] = t_res[j];
}
return false;
}

static void Main(string[] args)
{
int i;
int[] map = new int[10];
int[] res = new int[number.Length * 10];
for (i = 0; i < map.Length; ++i) map[i] = 0;
for (i = 0; i < res.Length; ++i) res[i] = 0;
for (i = 0; i < number.Length; ++i) ++map[number[i]];
for (i = 0; i < map.Length; ++i) b_map[i] = map[i];
if (!permute(0, map, res)) Console.WriteLine("-1");
}
}
}