본문 바로가기

Problem Solving/문제풀이

[CF] Codeforces Round #464 (Div. 2)

이번 CF는 총 A~F의 6개 문제로 이루어져 있었다.

 ABCD 50분만에 다풀고 E 하려다가 도저히 못하겠어서 반쯤 던져놓고 있었는데 끝나기 2분 전에 B 해킹이 들어와서 11초 남기고 B번 마지막 서브미션해서 맞았다. 덕분에 점수도 개판되고 레이팅도 100오를거 50밖에 안올랐다. 그래도 D번을 10분만에 풀어내서 점수에 아아주 큰 타격은 안간듯. D번이 이렇게 쉬울 줄 알았으면 DABC 순서로 풀걸 그랬다. 다음은 내가 푼 문제에 대한 솔루션들.

A. Love Triangle

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i.

We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.

Input

The first line contains a single integer n (2 ≤ n ≤ 5000) — the number of planes.

The second line contains n integers f1, f2, ..., fn (1 ≤ fi ≤ nfi ≠ i), meaning that the i-th plane likes the fi-th.

Output

Output «YES» if there is a love triangle consisting of planes on Earth. Otherwise, output «NO».

You can output any letter in lower case or in upper case.

Examples

input

Copy

5
2 4 5 1 3

output

YES

input

Copy

5
5 5 5 5 1

output

NO

Note

In first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.

In second example there are no love triangles.

A: 문제에서 요구하는 그대로 구현하면 된다. 나는 핵당할까봐 불안해서 쓸데없는 처리를 군데군데 했다.

P.S. Plane이 과연 뭘까.

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
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#define INF (2100000000)
 
using namespace std;
 
int arr[5005];
 
bool check(int x)
{
    int a,b,c;
    a=arr[x];
    b=arr[a];
    c=arr[b];
    if(x!=c) return false;
    if(x==|| x==|| a==b) return false;
    return true;
 
}
 
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&arr[i]);
    for(int i=1;i<=n;i++)
    {
        if(check(i))
        {
            printf("yes");
            return 0;
        }
    }
    printf("no");
    return 0;
}
 
cs


B. Hamster Farm

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.

Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.

Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.

Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.

Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.

Input

The first line contains two integers N and K (0 ≤ N ≤ 10181 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces.

The second line contains K integers a1a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.

Output

Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input.

If there are many correct answers, output any of them.

Examples

input

Copy

19 3
5 4 10

output

2 4

input

Copy

28 3
5 6 30

output

1 5

B: 그냥 돌면서 나머지 연산 해주는 문제다. 나는 범위 제대로 안보고 INF를 너무 작게 잡아서 따로 처리를 해줘야 했다. 이것때문에 레이팅 50점 날림 ㅡㅡ

P.S. 나도 햄스터를 $10^18$마리 키워보고 싶다. 

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
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#define INF (2100000000)
 
using namespace std;
 
 
 
int main()
{
    long long n,mi=-1,mii,ma;
    int m;
    scanf("%lld %d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        long long t;
        scanf("%lld",&t);
        long long a=n/t;
        long long b=n%t;
        if(mi==-1)
        {
            mi=b;
            ma=a;
            mii=i;
        }
        else if(mi>b)
        {
            mi=b;
            ma=a;
            mii=i;
        }
    }
    printf("%lld %lld",mii,ma);
    return 0;
}
 

cs

 

C. Convenient For Everybody

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.

Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.

Help platform select such an hour, that the number of people who will participate in the contest is maximum.

Input

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day.

The second line contains n space-separated integers a1a2, ..., an (1 ≤ ai ≤ 10 000), where ai is the number of people in the i-th timezone who want to participate in the contest.

The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).

Output

Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.

Examples

input

Copy

3
1 2 3
1 3

output

3

input

Copy

5
1 2 3 4 1
1 3

output

4

Note

In the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2hours in the third timezone. Only one person from the first timezone won't participate.

In second example only people from the third and the fourth timezones will participate.

C: 본격 D번보다 어려운 C번.

그냥 이렇게 생각하면 비교적 간단하게 풀 수 있다. 예를 들어 5개의 도시가 있고 s와 t가 각각 2, 4라고 하자.

 1

2

그러면 맨 처음에는 이 시간대의 사람들이 코포를 할 수 있다. 1시간 뒤, 2시간 뒤의... 상황은 이렇게 된다.

 2

3


 3

4



 5


결국은 코포를 칠수 있는 사람들의 범위는 왼쪽으로 한칸씩 밀려나므로 이를 슬라이딩 윈도우 기법을 통해서 최대값을 구해주면 된다. 이게 환형으로 되어있는 구조인데, 이를 펼쳐주면 훨씬 더 간단하게 구현이 가능하다. 근데 난 아직도 내가 왜 대회중에 배열을 3배로 펼쳤는지 이해가 되지 않는다...

P.S. 구현을 좀 더 깔끔하게 할 수 있을거같다. 처음에 오른쪽으로 미는걸로 잘못생각해서 코드가 이 사단이 난 것 같다.


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
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#define INF (2100000000)
 
using namespace std;
 
int main()
{
    int n,s,t,part=0,ma,mai;
    vector<int> v(300005);
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&v[n+n+n-i+1]);
        v[n+n-i+1]=v[n+n+n-i+1];
        v[n-i+1]=v[n+n+n-i+1];
    }
    scanf("%d %d",&s,&t);
    s=n-s+1;
    t=n-t+1;
    int k=s-t;
 
    for(int i=t+1;i<=s;i++)
        part+=v[i];
    ma=part;
    mai=0;
    int wh=0;
    for(int i=s+1;i<=n+n+n;i++)
    {
        part+=v[i];
        part-=v[i-k];
        wh++;
        if(ma<part)
        {
            ma=part;
            mai=wh;
        }
    }
    printf("%d",mai%n+1);
    return 0;
}
 
cs


D. Love Rescue

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.

This story could be very sad but fairy godmother (Tolya's grandmother) decided to help them and restore their relationship. She secretly took Tolya's t-shirt and Valya's pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya's grandmother should spend to rescue love of Tolya and Valya.

More formally, letterings on Tolya's t-shirt and Valya's pullover are two strings with same length n consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form (c1, c2) (where c1 and c2 are some lowercase English letters), which can arbitrary number of times transform a single letter c1 to c2 and vise-versa on both Tolya's t-shirt and Valya's pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells.

Input

The first line contains a single integer n (1 ≤ n ≤ 105) — the length of the letterings.

The second line contains a string with length n, consisting of lowercase English letters — the lettering on Valya's pullover.

The third line contains the lettering on Tolya's t-shirt in the same format.

Output

In the first line output a single integer — the minimum amount of mana t required for rescuing love of Valya and Tolya.

In the next t lines output pairs of space-separated lowercase English letters — spells that Tolya's grandmother should buy. Spells and letters in spells can be printed in any order.

If there are many optimal answers, output any.

Examples

input

Copy

3
abb
dad

output

2
a d
b a

input

Copy

8
drpepper
cocacola

output

7
l e
e d
d c
c p
p o
o r
r a

Note

In first example it's enough to buy two spells: ('a','d') and ('b','a'). Then first letters will coincide when we will replace letter 'a' with 'd'. Second letters will coincide when we will replace 'b' with 'a'. Third letters will coincide when we will at first replace 'b' with 'a' and then 'a' with 'd'.

D번: 굉장히 다양한 풀이법이 있을거라고 추측한다. 일단 내 풀이법은 Union-Find 트리를 이용한다. 첫 글자부터 비교해 가면서 만약에 두 글자가 다른 집합에 속해있다면 merge하면서 마법을 쓰고, 아니라면 그냥 넘기면 된다. 너무나 간단하게 이것이 반드시 최적해임을 증명할 수 있다. 넘나쉬운것 ㅇㅅㅇ 다른 사람들 중에서는 최소신장트리같은걸 쓴사람도 있었고... 하여튼 UF 쓰는게 제일 편하고 빠르다. 굳.

P.S. 나도 연애를 하고 싶다.


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
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#define INF (2100000000)
 
using namespace std;
 
typedef struct DisJointSet
{
    vector<int> parent;
    vector<int> ra;
    DisJointSet(int n)
    {
        parent.assign(n+1,0);
        ra.assign(n+1,0);
        for(int i=0;i<=n;i++)
            parent[i]=i;
    }
    int fi(int a)
    {
        if(parent[a]==a) return a;
        else return parent[a]=fi(parent[a]);
    }
    void un(int a, int b)
    {
        a=fi(a); b=fi(b);
        if(a==b) return;
        if(ra[a]>ra[b]) swap(a,b);
        parent[b]=a;
        if(ra[a]==ra[b]) ra[b]++;
    }
}DJS;
 
int ch(char x)
{
    return x-'a';
}
 
char rch(int x)
{
    return x+'a';
}
 
int main()
{
    int n;
    vector<pair<int,int> > ans;
    char a[100005],b[100005];
    scanf("%d",&n);
    scanf(" %s",a);
    scanf(" %s",b);
 
    DJS S(30);
 
    for(int i=0;i<n;i++)
    {
        int p=ch(a[i]);
        int q=ch(b[i]);
        if(S.fi(p)==S.fi(q)) continue;
        S.un(p,q);
        ans.push_back(make_pair(p,q));
    }
 
    printf("%d\n",ans.size());
    for(int i=0;i<ans.size();i++)
    {
        int p=ans[i].first;
        int q=ans[i].second;
        printf("%c %c\n",rch(p),rch(q));
    }
 
    return 0;
}
 
 
 
 
cs


E. Maximize!

time limit per test

3 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given a multiset S consisting of positive integers (initially empty). There are two kind of queries:

1.   Add a positive integer to S, the newly added integer is not less than any number in it.

2.   Find a subset s of the set S such that the value http://codeforces.com/predownloaded/48/b9/48b9fb7119c80aff7251ee4907a16222751e8f0e.png is maximum possible. Here max(s) means maximum value of elements in shttp://codeforces.com/predownloaded/2e/ad/2ead08f8ca08becac143c09ae17e8efd33bb05d8.png — the average value of numbers in s. Output this maximum possible value of http://codeforces.com/predownloaded/48/b9/48b9fb7119c80aff7251ee4907a16222751e8f0e.png.

Input

The first line contains a single integer Q (1 ≤ Q ≤ 5·105) — the number of queries.

Each of the next Q lines contains a description of query. For queries of type 1 two integers 1 and x are given, where x (1 ≤ x ≤ 109) is a number that you should add to S. It's guaranteed that x is not less than any number in S. For queries of type 2, a single integer 2 is given.

It's guaranteed that the first query has type 1, i. e. S is not empty when a query of type 2 comes.

Output

Output the answer for each query of the second type in the order these queries are given in input. Each number should be printed in separate line.

Your answer is considered correct, if each of your answers has absolute or relative error not greater than 10 - 6.

Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if http://codeforces.com/predownloaded/d7/f1/d7f14565cb674951cdc8dd8d1ba5f9dd9a1758b6.png.

Examples

input

Copy

6
1 3
2
1 4
2
1 8
2

output

0.0000000000
0.5000000000
3.0000000000

input

Copy

4
1 1
1 4
1 5
2

output

2.0000000000

E번: 더블 포인터로 뭔가를 한다고 하던데, 나는 스택으로 어쭙잖게 구현했다가 1패널티만 먹었다. 추후에 풀이가 이해되면 다시 알림.

P.S. 수학 시러



F. Cutlet

time limit per test

4 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Arkady wants to have a dinner. He has just returned from a shop where he has bought a semifinished cutlet. He only needs to fry it. The cutlet should be fried for 2n seconds, in particular, it should be fried for n seconds on one side and n seconds on the other side. Arkady has already got a frying pan and turn on fire, but understood that maybe he won't be able to flip the cutlet exactly after n seconds after the beginning of cooking.

Arkady is too busy with sorting sticker packs in his favorite messenger and can flip the cutlet only in some periods of time. Namely, there are k periods of time in which he can do it, the i-th of them is an interval of time from li seconds after he starts cooking till ri seconds, inclusive. Arkady decided that it's not required to flip the cutlet exactly in the middle of cooking, instead, he will flip it several times in such a way that the cutlet will be fried exactly n seconds on one side and n seconds on the other side in total.

Help Arkady and find out if it's possible for him to cook the cutlet, if he is able to flip the cutlet only in given periods of time; and if yes, find the minimum number of flips he needs to cook the cutlet.

Input

The first line contains two integers n and k (1 ≤ n ≤ 100 0001 ≤ k ≤ 100) — the number of seconds the cutlet should be cooked on each side and number of periods of time in which Arkady can flip it.

The next k lines contain descriptions of these intervals. Each line contains two integers li and ri (0 ≤ li ≤ ri ≤ 2·n), meaning that Arkady can flip the cutlet in any moment starting from li seconds after the beginning of cooking and finishing at ri seconds after beginning of cooking. In particular, if li = ri then Arkady can flip the cutlet only in the moment li = ri. It's guaranteed that li > ri - 1 for all 2 ≤ i ≤ k.

Output

Output "Hungry" if Arkady won't be able to fry the cutlet for exactly n seconds on one side and exactly n seconds on the other side.

Otherwise, output "Full" in the first line, and the minimum number of times he should flip the cutlet in the second line.

Examples

input

Copy

10 2
3 5
11 13

output

Full
2

input

Copy

10 3
3 5
9 10
11 13

output

Full
1

input

Copy

20 1
3 19

output

Hungry

Note

In the first example Arkady should flip the cutlet in time moment 3 seconds after he starts cooking and in time moment 13 seconds after he starts cooking.

In the second example, Arkady can flip the cutlet at 10 seconds after he starts cooking.

 

F번: 문제도 읽어보지 않았다.

P.S. 돈까스를 먹고싶을 뿐이다.



이번 코드포스 총평:

끝나기 2분전에 B번 해킹을 당해버렸다. 다음부터는 범위를 좀더 명확하게 보는 습관을 들여야겠고, INF같은건 미리미리 선언해줘야겠고, 그리고 무엇보다 해킹당한 B번의 문제점을 30초만에 찾아내어 부들부들 떨리는 손으로 에러를 수정해서 마감 11초 전에 제출해 어셉을 받을 수 있게 해준 내 로지텍 무소음 마우스에게 경의를 표한다. 이번에 레이팅이 대강 1570정도가 되었는데 화요일 코포를 잘 치면 블루로 올라갈수도 있을 것 같다. 그랬으면 좋겠다. 미리 라이브러리를 구성해 놓는 것이 얼마나 중요한지 이제 알았다. 미리미리 구성해놔야지. 그래도 D번까지 50분 내로 클리어해서 기분은 좋다 ㅎㅎ


'Problem Solving > 문제풀이' 카테고리의 다른 글

[BOJ] 10840 구간 성분  (0) 2018.07.19
[BOJ] 2472 체인점  (0) 2018.07.18
[BOJ] 1504 특정한 최단 경로  (0) 2018.02.12
[BOJ] 1916 최소비용 구하기  (0) 2018.02.12
[BOJ] 13306 트리  (0) 2018.02.12