-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC1077_CF.java
More file actions
94 lines (75 loc) · 2.17 KB
/
Copy pathC1077_CF.java
File metadata and controls
94 lines (75 loc) · 2.17 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.*;
public class C1077_CF {
public static void main(String[]args){
Scanner scn = new Scanner(System.in);
int n=scn.nextInt();
long arr[]=new long[n];
long sum=0;
HashMap<Long,Integer>map=new HashMap<>();
for(int i=0;i<n;i++){
arr[i]=scn.nextLong();
sum+=arr[i];
map.put(arr[i],map.getOrDefault(arr[i],0)+1);
}
ArrayList<Integer>list=new ArrayList<>();
for(int i=0;i<n;i++){
long rem=sum-arr[i];
if(rem%2!=0)continue;
long need=rem/2;
map.put(arr[i],map.get(arr[i])-1);
if(map.getOrDefault(need,0)>0){
list.add(i+1);
}
map.put(arr[i],map.get(arr[i])+1);
}
System.out.println(list.size());
for(int x:list){
System.out.print(x + " ");
}
System.out.println();
}
}
// IMPORTANT:
// Use long for sum and `need`.
// Casting (remainingSum / 2) to int causes overflow for large values,
// leading to wrong HashMap lookups and WA on CF.
// If sum is long → map keys must be long too.
/*
o(n3) soln:-
import java.util.*;
public class C1077_CF {
public static void main(String[]args){
Scanner scn = new Scanner(System.in);
int n=scn.nextInt();
int arr[]=new int[n];
int sum=0;
for(int i=0;i<n;i++){arr[i]=scn.nextInt(); sum+=arr[i];}
ArrayList<Integer>list=new ArrayList<>();
for(int x:arr){
list.add(x);
}
HashSet<Integer>set=new HashSet<>();
for(int i=0;i<n;i++){
int curr=sum-arr[i];
for(int j=0;j<n;j++){
if(i==j){
continue;
}
int x=curr-arr[j];
if(list.contains(x) && x!=arr[i]){
set.add(i+1);
}
}
}
if(set.isEmpty()){
System.out.println(0);
}else{
System.out.println(set.size());
for(int s:set){
System.out.print(s + " ");
}
System.out.println();
}
}
}
*/