반응형

문제 출처 :


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



알고리즘 분석 :


문제 해결에 필요한 사항

1. manacher 알고리즘 ::  http://www.crocus.co.kr/1075?category=209527


manacher 알고리즘으로 해결 할 수 있는 문제이다.


시간 복잡도는 O(n + q)이고 manacher 알고리즘을 통해 팰린드롬을 모두 모아 둔 후,


쿼리에서 s와 e에 대해 처리를 해주면 된다.


이때 쿼리는 다음과 같다.


  while (q--)

   {

      int s, e;

      scanf("%d %d", &s, &e);

      s--, e--;

      s *= 2;

      e *= 2;


      int r = A[(s + e) / 2];

        

      if ((s + e) / 2 + r >= e)

         printf("1\n");

      else

         printf("0\n");

   }


(s + e) / 2 + r >= e의 의미는 현재 e 인덱스가 r이 가지는 팰린드롬 내부에 포함되고 있다면 1이고 그게 아니면 0이라는 것이다.


이때 문자열은 1 2 3이라면 1#2#3같은 방식으로 구현하여 해결하였다.






소스 코드 : 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <memory.h>
 
using namespace std;
 
const int MAXN = 1000001 * 2;
 
string tmp, str;
 
int A[MAXN];
 
void manachers(string S, int N)
{
    int r = 0, p = 0;
    for (int i = 0; i < N; i++)
    {
        if (i <= r)
            A[i] = min(A[* p - i], r - i);
        else
            A[i] = 0;
 
        while (i - A[i] - >= && i + A[i] + < N && S[i - A[i] - 1== S[i + A[i] + 1])
            A[i]++;
 
        if (r < i + A[i])
        {
            r = i + A[i];
            p = i;
        }
    }
}
 
int main()
{
    int n;
    scanf("%d"&n);
 
    for (int i = 0; i < n; i++)
    {
        int val;
        scanf("%d"&val);
        tmp.push_back(val + '0');
    }
    int len = tmp.size();
    str = tmp[0];
 
    for (int i = 1; i < len; i++)
    {
        str += '#';
        str += tmp[i];
    }
    
    manachers(str, str.size());
 
    int q;
    scanf("%d"&q);
    while (q--)
    {
        int s, e;
        scanf("%d %d"&s, &e);
        s--, e--;
        s *= 2;
        e *= 2;
 
        int r = A[(s + e) / 2];
        if ((s + e) / + r >= e)
            printf("1\n");
        else
            printf("0\n");
    }
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus

반응형

'Applied > 알고리즘 문제풀이' 카테고리의 다른 글

[3613번] Java vs C++  (0) 2017.11.24
[11046번] 팰린드롬?  (0) 2017.11.24
[1254번] 팰린드롬 만들기  (0) 2017.11.22
[1254번] 팰린드롬 만들기  (0) 2017.11.19
[14846번] 직사각형과 쿼리  (4) 2017.11.17