반응형

문제출처

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


dp문제이나 n이 충분히 작기때문에 dfs로도 풀 수 있는 문제이다. 삼성기출문제인데 dp개념이 확실하지 않아 점화식을 세우는데 어려움이 있었다 .

풀이 과정

/**
* day 1 2 3 4 5 6 7
* =====================================
* t 3 5 1 1 2 4 2
* p 10 20 10 20 15 40 200
*
* i에서 시작해서 퇴사일 까지 최대 값을 dp[i]에 저장합니다.
* dp[i]는 두가지 중 최대값을 저장하면 된다. (i == 일)
* 1) 오늘의 스케쥴을 하는 경우 : dp[i + t[i]] + p[i]
* 2) 오늘의 스케쥴을 안 하는 경우 : dp[i+1]
/*
* 즉 solve(0) = Math.max(solve(1), solve(0 + t[0]) + p[0])
* .
* .
* .
* .
* .
* solve(6) = Math.max(solve(7), solve(8)+200
*
* 과 같이 나열된다. 하지만 여기서 7일까지만 일하므로 8일차는 범위를 벗어난 경우이다.
* 때문에 -값을 주어 max에 영향을 주지 않도록 조치한다.
* 이 재귀를 풀어서 역으로 추적하면 쉽게 답을 구할 수 있다.
*/


소스코드

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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
 
public class Main {
 
    public static final int INF = 0x7fffffff;
    public static final int MAX =16;
    public static int[] t = new int[MAX];
    public static int[] p = new int[MAX];
    public static int[] dp = new int[MAX];
    public static int n;
 
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        // input data...
        for (int i = 0; i <n; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
 
            t[i] = Integer.parseInt(st.nextToken());
            p[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.fill(dp, -1);
        int ret=solve(0);
        System.out.println(ret);
    }
 
    public static int solve(int s) {
        if(s==n)
            return 0;
        if(s>n)
            return -INF;
 
        int ret=dp[s];
        if(ret!=-1)
            return ret;
 
        ret=Math.max(solve(s+1), solve(s+t[s]) + p[s]);
        return ret;
    }
}
cs



아래와 같은 풀이도 존재한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cstdio>
using namespace std;
int dp[25];
int max(int a, int b) {
    return a > b ? a : b;
}
int main() {
    int N;
    int t, p;
    scanf("%d"&N);
    for (int i = 0; i < N; i++) {
        
        scanf("%d %d"&t, &p);
 
        dp[i + 1= max(dp[i + 1], dp[i]);
        dp[i + t] = max(dp[i + t], dp[i] + p);
 
    }
 
    printf("%d\n", dp[N]);
}
 
cs


반응형

'Algorithm' 카테고리의 다른 글

[SWEA 1245] 균형점  (0) 2019.01.15
[BOJ 1463] 1로 만들기  (0) 2019.01.14
[BOJ 1182] 부분집합의 합  (0) 2019.01.14
[BOJ 1543] 문서 검색  (0) 2019.01.08
[BOJ 2941] 크로아티아 알파벳  (0) 2019.01.07
반응형

문제출처

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



직관적으로 전체 탐색을 하니까 런타임에러가 나와 비트마스크 기법을 사용했다.


소스코드

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
#include <iostream>
#include <algorithm>
 
using namespace std;
 
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    int n, s;
    int set[21];
    cin >> n >> s;
    for (int i = 0; i < n; i++cin >> set[i];
 
    int sum = 0;
    int cnt = 0;
    for (int i = 1; i < (1 << n); i++) {    // 2^n 만큼 반복
        sum = 0;
        for (int j = 0; j < n; j++) {
            if (i&(1 << j))                    
                sum += set[j];
        }
        if (sum == s)
            cnt++;
    }
    cout << cnt;
 
    return 0;
}
cs


반응형

'Algorithm' 카테고리의 다른 글

[BOJ 1463] 1로 만들기  (0) 2019.01.14
[BOJ 14501] 퇴사  (0) 2019.01.14
[BOJ 1543] 문서 검색  (0) 2019.01.08
[BOJ 2941] 크로아티아 알파벳  (0) 2019.01.07
[BOJ 1316] 그룹 단어 체크  (0) 2019.01.07
반응형

문제출처

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


반복문을 2번 써서 풀이할 수도 있으나 좋은 방법은 아니다. stl을 사용하기는 했지만 사용하지 않고 더 좋은 방법을 생각해 봐야겠다.


소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    string doc, word;
    int cnt = 0;
    getline(cin, doc);
    getline(cin, word);
 
    auto tmp = doc.find(word);
    while (tmp != string::npos) {    // 찾는 문자열이 없을때까지 반복
        cnt++;
        // 해당 글자를 찾은 위치부터 다시 찾는다.
        tmp = doc.find(word, tmp + word.size());
    }
    cout << cnt;
}
cs


반응형

'Algorithm' 카테고리의 다른 글

[BOJ 14501] 퇴사  (0) 2019.01.14
[BOJ 1182] 부분집합의 합  (0) 2019.01.14
[BOJ 2941] 크로아티아 알파벳  (0) 2019.01.07
[BOJ 1316] 그룹 단어 체크  (0) 2019.01.07
[BOJ 2908] 상수  (0) 2019.01.07
반응형

문제출처

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


순서대로 if로 묶어주면 된다


소스코드

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
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
 
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    string str;
    int ret = 0;
    cin >> str;
 
    for (int i = 0; i < str.size(); i++) {
        ret++;
        if (str[i] == 'c' && (str[i + 1== '=' || str[i + 1== '-'))
            i++;
        else if (str[i] == 'd') {
            if (str[i + 1== '-')
                i++;
            else if (str[i + 1== 'z' && str[i + 2== '=')
                i += 2;
        }
        else if ((str[i] == 'l' || str[i] == 'n'&& str[i + 1== 'j')
            i++;
        else if ((str[i] == 's' || str[i] == 'z'&& str[i + 1== '=')
            i++;
    }
 
    cout << ret;
    return 0;
}
cs


반응형

'Algorithm' 카테고리의 다른 글

[BOJ 1182] 부분집합의 합  (0) 2019.01.14
[BOJ 1543] 문서 검색  (0) 2019.01.08
[BOJ 1316] 그룹 단어 체크  (0) 2019.01.07
[BOJ 2908] 상수  (0) 2019.01.07
[BOJ 10809] 알파벳 찾기  (0) 2019.01.07
반응형

문제 출처

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


i번째 문자와 i-1번째 문자가 같으면 연속된 문자이므로 같은 그룹이다. 

앞에서 동일한 문자가 나오고 i번째와 i-1번째 문자가 다른경우 그룹에 속해있지 않은 경우이므로 check배열을 사용하면 쉽게 풀수 있다.


소스코드

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
#include <iostream>
#include <string>
 
using namespace std;
 
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n;
    string str;
    int ret = 0;
    cin >> n;
    while (n--) {
        bool c[26= { 0 };
        bool flag = 0;
        cin >> str;
        c[str[0- 97= 1;
        for (int i = 1; i < str.size(); i++) {
            int cur = str[i] - 97;        // 현재 글자
            int pre = str[i - 1- 97;    // 이전 글자
            if (c[cur] && cur != pre)    flag = 1;    // 앞에 동일한 문자가 나오고 현재글자와 이전글자가 다른경우 flag를 true
            c[cur] = 1;                    // 동일한 문자가 나왔으므로 check를 한다.
        }
        if (!flag)                        // 해당 문자열이 그룹문자일 경우
            ret++;
    }
 
    cout << ret;
    return 0;
}
 
cs


반응형

'Algorithm' 카테고리의 다른 글

[BOJ 1543] 문서 검색  (0) 2019.01.08
[BOJ 2941] 크로아티아 알파벳  (0) 2019.01.07
[BOJ 2908] 상수  (0) 2019.01.07
[BOJ 10809] 알파벳 찾기  (0) 2019.01.07
[BOJ_11724] 연결 요소의 개수  (0) 2019.01.07
반응형

문제 출처

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


소스코드

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
#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int reverse(int num) {
    int a = num / 100;
    int b = (num % 100/ 10;
    int c = num % 10;
    int ret = c * 100 + b * 10 + a;
    return ret;
}
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    int a, b;
    cin >> a >> b;
    a = reverse(a);
    b = reverse(b);
    if (a > b)
        cout << a;
    else
        cout << b;
    return 0;
}
cs


반응형
반응형

문제출처

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


해당 문자를 찾을 경우 위치 배열에 값을 넣어준다.


소스코드

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
#include <iostream>
#include <vector>
#include <string>
 
using namespace std;
 
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    string str;
    cin >> str;
 
    // 알파벳 갯수만큼 -1로 초기화
    vector<int> v(26-1);
    for (int i = 0; i < str.size(); i++) {
 
        // 소문자 a의 ASCII값 = 97
        if (v[str.at(i) - 97== -1)
            v[str.at(i) - 97= i;
    }
 
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
        cout << *it << " ";
 
    return 0;
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <string.h>
int main() {
    char s[101];
    int loc[26];
    memset(loc, -1sizeof(loc));
    scanf("%s"&s);
    int len = strlen(s);
    while(len--) loc[s[len] - 'a'= len;
    for(int i=0; i<26; i++printf("%d ", loc[i]);
    return 0;
}
cs


반응형

'Algorithm' 카테고리의 다른 글

[BOJ 1316] 그룹 단어 체크  (0) 2019.01.07
[BOJ 2908] 상수  (0) 2019.01.07
[BOJ_11724] 연결 요소의 개수  (0) 2019.01.07
[카카오 2019] 코딩테스트 - 무지의 먹방 라이브  (0) 2019.01.07
[BOJ 11004] K번째 수  (0) 2019.01.07
반응형

문제출처

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


dfs / bfs 두가지 모두 풀이가 가능하다. 하지만 분류가 bfs로 되어있어 bfs로 풀이하였다. bfs 개념을 익히는데 도움이 되는 문제


소스코드

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
#include <iostream>
#include <vector>
#include <queue>
 
using namespace std;
int v, e;    //vertex, edge
int result;
bool visit[1001];
bool g[1001][1001];
void bfs(int s) {
    queue<int> q;
    q.push(s);
    visit[s] = 1;
    
    while (!q.empty()) {
        s = q.front();
        q.pop();
 
        for (int i = 1; i <= sizeof(g[s]); i++) {
            if (g[s][i] && !visit[i]) {
                q.push(i);
                visit[i] = 1;
            }
        }
    }
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> v >> e;
    int start, end;
    // init graph...
    for (int i = 1; i <= e; i++) {
        cin >> start >> end;
        g[start][end= 1;
        g[end][start] = 1;
    }
 
    for (int i = 1; i <= v; i++) {
        if (!visit[i]) {
            bfs(i);
            result++;
        }
    }
 
    cout << result;
    return 0;
}
cs




반응형

'Algorithm' 카테고리의 다른 글

[BOJ 2908] 상수  (0) 2019.01.07
[BOJ 10809] 알파벳 찾기  (0) 2019.01.07
[카카오 2019] 코딩테스트 - 무지의 먹방 라이브  (0) 2019.01.07
[BOJ 11004] K번째 수  (0) 2019.01.07
[BOJ 3047] ABC  (0) 2019.01.06
반응형

문제출처

https://programmers.co.kr/learn/courses/30/lessons/42891


효율성 테스트가 있는 문제이다. 

전체 탐색을 하면 효율성 테스트에서 통과하지 못한다. idea는 정렬을 통해 가장 작은 값의 시간을 한번에 빼는 방법을 사용하였다.


소스코드

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
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
bool comp(pair<intint> a, pair<intint> b) {
    return a.second < b.second;
}
 
int solution(vector<int> food_times, long long k) {
    vector<pair<intint>> food;
    int size = food_times.size();
    for(int i=0; i<size; i++)
        food.push_back(make_pair(food_times.at(i), i+1));
    
    sort(food.begin(), food.end());
    
    int time=0;
    for(vector<pair<intint>>::iterator it=food.begin(); it!=food.end(); it++size--) {
        long long leadTime = (long long)(it->first - time) * size;
        if(leadTime == 0)
            continue;
        
        if(leadTime <= k) {
            k-=leadTime;
            time=it->first;
        } else {
            k%=size;
            sort(it, food.end(), comp);
            return (it+k)->second;
        }       
    }
    return -1;
}
cs




반응형

'Algorithm' 카테고리의 다른 글

[BOJ 10809] 알파벳 찾기  (0) 2019.01.07
[BOJ_11724] 연결 요소의 개수  (0) 2019.01.07
[BOJ 11004] K번째 수  (0) 2019.01.07
[BOJ 3047] ABC  (0) 2019.01.06
[BOJ 1987] 알파벳  (0) 2019.01.05
반응형

문제 출처

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


단순 정렬하는 문제이다...

sort함수 사용


소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <algorithm>
#include <vector>
 
using namespace std;
 
int n, k;
vector<int> v;
 
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin>>n>>k;
    v.resize(n);
 
    for(int i=0; i<n; i++)
        cin>>v[i];
 
    sort(v.begin(), v.end());
    cout<<v[k-1]<<endl;
}
cs




반응형

'Algorithm' 카테고리의 다른 글

[BOJ_11724] 연결 요소의 개수  (0) 2019.01.07
[카카오 2019] 코딩테스트 - 무지의 먹방 라이브  (0) 2019.01.07
[BOJ 3047] ABC  (0) 2019.01.06
[BOJ 1987] 알파벳  (0) 2019.01.05
[카카오 2019] 코딩테스트 - 오픈채팅방  (0) 2019.01.03

+ Recent posts