二进制中1的个数
给定一个长度为 n 的数列,请你求出数列中每个数的二进制表示中 1 的个数
import java.util.*;
public class Main{
static int N = 100010;
static long[] a = new long[N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 0; i < n; i ++) a[i] = sc.nextInt();
for(int i = 0; i < n; i ++){
int t = 0;
while(a[i] != 0){
t += a[i] & 1;
a[i] >>= 1;
}
System.out.print(t + " ");
}
}
}
区间合并
给定n
个区间 [li,ri]
,要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3] 和 [2,6] 可以合并为一个区间 [1,6]。
import java.util.*;
class PII{
long l;
long r;
public PII(long l, long r){
this.l = l;
this.r = r;
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<PII> list = new ArrayList<>();
for(int i = 0; i < n; i ++){
int l, r;
l = sc.nextInt(); r = sc.nextInt();
PII pii = new PII(l, r);
list.add(pii);
}
list.sort(new Comparator<PII>(){
public int compare(PII p1, PII p2){
return (int)(p1.l - p2.l);
}
});
int cnt = 1;
PII cur = list.get(0);
for(int i = 1; i < list.size(); i ++){
PII p = list.get(i);
if(cur.r < p.l){
cnt ++;
cur = p;
}else{
if(cur.r < p.r) cur = p;
}
}
System.out.println(cnt);
}
}
区间和
题目
假定有一个无限长的数轴,数轴上每个坐标上的数都是 0。
现在,我们首先进行 n 次操作,每次操作将某一位置 x 上的数加 c。
接下来,进行 m 次询问,每个询问包含两个整数 l 和 r,你需要求出在区间 [l,r] 之间的所有数的和。
输入格式
第一行包含两个整数 n 和 m。
接下来 n 行,每行包含两个整数 x 和 c。
再接下来 m 行,每行包含两个整数 l 和 r。
输出格式
共 m 行,每行输出一个询问中所求的区间内数字和。
解题步骤
思路:将使用到的下标映射到新开辟的连续的数组下标。
- 保存使用到的下标进行排序、去重
- 二分找到下标在新数组中映射的位置
- 利用前缀和求区间和
import java.util.*;
class PII implements Comparable<PII>{
int first;
int second;
public PII(int first, int second){
this.first = first;
this.second = second;
}
@Override
public int compareTo(PII o){
return this.first - o.first;
}
}
public class Main{
static int N = 300010;
static int[] a = new int[N];
static int[] s = new int[N];
static List<Integer> alls = new ArrayList<>();
static List<PII> add = new ArrayList<>();
static List<PII> query = new ArrayList<>();
public static int find(int x){
int l = 0, r = alls.size() - 1;
while(l < r){
int mid = l + r >> 1;
if(alls.get(mid) >= x) r = mid;
else l = mid + 1;
}
return r + 1;
}
public static void unique(){
int j = 0;
for(int i = 0; i < alls.size(); i ++){
if(i == 0 || alls.get(i) != alls.get(i - 1)){
alls.set(j ++, alls.get(i));
}
}
int k = j;
while(alls.size() > j) alls.remove(k);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n, m;
n = sc.nextInt(); m = sc.nextInt();
for(int i = 0; i < n; i ++){
int x, c;
x = sc.nextInt(); c = sc.nextInt();
add.add(new PII(x, c));
alls.add(x);
}
for(int i = 0; i < m; i ++){
int l, r;
l = sc.nextInt(); r = sc.nextInt();
query.add(new PII(l, r));
alls.add(l);
alls.add(r);
}
Collections.sort(alls);
unique();
for(PII p : add){
int x = find(p.first);
a[x] += p.second;
}
for(int i = 1; i <= alls.size(); i ++) s[i] = s[i - 1] + a[i];
for(PII p : query){
int l, r;
l = find(p.first);
r = find(p.second);
System.out.println(s[r] - s[l - 1]);
}
}
}