[SWEA] 9229 한빈이와 Spot Mart

Time Lapse :9min 0sec

9229.cpp

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
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> weight;
int N,M;
int main(void){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int TC;
cin>>TC;
for(int i=1;i<=TC;i++){
int ans=-1;
cin>>N>>M;
weight.clear();
weight.resize(N);
for(int j=0;j<N;j++)
cin>>weight[j];
sort(weight.begin(),weight.end());
for(int j=N-1;j>=0;j--){
if(weight[j]>M)
continue;
for(int k=j-1;k>=0;k--){
if((weight[j]+weight[k])>M)
continue;
ans=max(ans,weight[k]+weight[j]);
break;
}
}
cout<<"#"<<i<<" "<<ans<<endl;
}
}

9229.java

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
import java.io.*;
import java.util.*;

public class Solution {
public static int m, n, ans, i, T, tc = 1;
public static int[] snacks = new int[1000];
public static Reader r = new Reader();
public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
T = r.nextInt();
while (T-- != 0) {
n = r.nextInt();
m = r.nextInt();

for(i = 0, ans = -1; i < n; ++i)
snacks[i] = r.nextInt();

Arrays.sort(snacks, 0, n);
if(snacks[0] + snacks[1] <= m)
for (i = 1; i < n && snacks[i] <= m; ++i)
ans = Math.max(ans, snacks[i] + binarySearch(m - snacks[i], i));

bw.write("#" + tc++ + " " + ans + "\n");
}
bw.flush();
}

static int binarySearch(int target, int r) {
int l = 0, m, ret = -987654321;
while(l < r) {
m = (l+r)>>1;
if(snacks[m] == target) return target;
if(snacks[m] < target) {
l = m + 1;
ret = Math.max(ret, snacks[m]);
}
else r = m;
}
return ret;
}

static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;

public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}

public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
do {
ret = (ret<<3) + (ret<<1) + (c & 0b1111);
} while ((c = read()) >= '0' && c <= '9');

return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}

private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}

}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/04/PS/SWEA/9229/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.