Codeforces 1B - Spreadsheets

Problem - 1B - Codeforces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program {
    // A, B, C, ..., Y, Z, AA, AB, AC, ... を返す
    static IEnumerable<string> Seq() {
        // A = 1, B = 2, Y = 25, Z = 26 にマップする
        var cs = new List<int>() { 1 }; // cs[0] が最下位の桁
        for (;;) {
            yield return string.Join("", Enumerable.Reverse(cs).Select(c => (char)('A' + c - 1)));

            cs[0]++;
            for (int i = 0; i < cs.Count; i++) {
                if (cs[i] > 26) {
                    cs[i] = 1;
                    if (i+1 < cs.Count) {
                        cs[i+1]++;
                    }
                    else { // 新しい桁の追加
                        cs.Add(1);
                        break;
                    }
                }
            }
        }
    }

    // A => 1, B => 2, ... Z => 26, AA => 27 の変換を行う
    static int ConvertInt(string s) {
        int n = 0;
        foreach (var c in s) {
            n = 26 * n + (c - 'A' + 1);
        }
        return n;
    }

    // 1 => A, 2 => B, ..., 26 => Z, 27 => AA の変換を行う
    static string ConvertString(int n) {
        var cs = new List<char>();
        while (n > 0) {
            int m = (n-1) % 26;
            cs.Add((char)(m + 'A'));
            n = (n-1) / 26;
        }
        return string.Join("", Enumerable.Reverse(cs));
    }

    static void Main() {
        var regRC = new Regex(@"R([0-9]+)C([0-9]+)");
        var regAN = new Regex(@"([A-Z]+)([0-9]+)");

        int n = int.Parse(Console.ReadLine());
        for (int i = 0; i < n; i++) {
            var s = Console.ReadLine();

            var m = regRC.Match(s);
            if (m.Success) {
                var r = m.Groups[1].Value;
                var c = int.Parse(m.Groups[2].Value);
                Console.WriteLine("{0}{1}", ConvertString(c), r);
            }
            else {
                m = regAN.Match(s);
                var c = m.Groups[1].Value;
                var r = m.Groups[2].Value;
                Console.WriteLine("R{0}C{1}", r, ConvertInt(c));
            }
        }
    }
}