[BOJ/C#] 15829 Hashing

Algorithm 2023. 1. 27. 21:37
반응형

https://www.acmicpc.net/problem/15829

 

15829번: Hashing

APC에 온 것을 환영한다. 만약 여러분이 학교에서 자료구조를 수강했다면 해시 함수에 대해 배웠을 것이다. 해시 함수란 임의의 길이의 입력을 받아서 고정된 길이의 출력을 내보내는 함수로 정

www.acmicpc.net

 

50점 

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;

namespace BOJ_15829
{
    class Program
    {
        static void Main(string[] args)
        {
            //abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
            StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
            StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));

            int L = int.Parse(sr.ReadLine());
            string str = sr.ReadLine();
            long[] arr = new long[str.Length];
            int m = 1234567891;
            long sum = 0;
            for (int i = 0; i < str.Length; i++)
            {
                arr[i] = (str[i] - 97) + 1;
                sum += arr[i] * ((long)Math.Pow(31, i) % m);
            }
            sw.WriteLine(sum);
            

            sr.Close();
            sw.Close();
        }
    }
}

 

 

 

 

 

 

100점 

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;

namespace BOJ_15829
{
    class Program
    {
        static void Main(string[] args)
        {
            //abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
            StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
            StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));

            int L = int.Parse(sr.ReadLine());
            string str = sr.ReadLine();
            long m = 1234567891;
            long sum = 0;
            for (int i = 0; i < L; i++)
            {
                long num = str[i] - 97 + 1;
                long mul = 1;
                for (int j = 0; j < i; j++)
                {
                    mul *= 31;
                    mul %= m;
                }

                sum += num * mul;
                sum %= m;
                // sw.WriteLine(sum);    
            }
            sw.WriteLine(sum);
            sr.Close();
            sw.Close();
        }
    }
}
반응형
: