2019 Ji Suan Ke Blue Bridge Cup Simulation Tournament III

 

Fill in the blanks: Number split

 

Idea: The recursive push was wrong at the beginning, use dfs instead

Code:

#include<iostream>
using namespace std;
int ans;

void dfs(int x, int sum){//表示从x开始搜,sum为当前数字和 
	if(sum == 10){
		ans++;
		return ;
	}
	//记住i从x开始搜的这一剪枝,不仅仅可以提升效率
	//更重要的是可以保证搜索出来的结果不会重复,是有序的 
	for(int i = x; i <= 10 - sum; i++){
		dfs(i, sum + i);
	}
}


int main(){
	dfs(1, 0);
	cout << ans << endl;
	return 0;
}

 


Programming: Friends

In Suan Country, there are n households of fishermen living on the coastline, neatly arranged in a straight line. The house of each fisherman is represented by a coordinate pi​, and the activity radius of each fisherman is d. That is to say, two houses whose distance is less than or equal to d, the two fishermen know each other and are friends.

So how many fishermen know each other in Suan Country?

input format

Enter two integers n, d on the first line.

The second line inputs n integers pi​, representing the coordinates of each fisherman’s house (there are pi with the same coordinates).

output format

Output an integer indicating how many pairs of fishermen know each other.

data range

For 50% of the data range: 1≤n≤10^3.

For 100% data range: 1≤n≤10^5, 1≤d≤10^4, 1≤pi​≤10^8.

Sample input copy

5 10
10 12 16 37 40

Sample output copy

4

 

Ideas:

Start with brute force, double for loop to enumerate all answers

After reading the solution, I realized that I am a younger brother. I never thought of using such a useful upper_bound binary.

awsl

Code:

#include<iostream>
#include<algorithm>
#define ll long long 
using namespace std;
int n, d;
int p[101000];  //这题还有两个坑点,一个是数组要开到1e6 
ll sum;      //第二个就是sum不用ll会爆 

int main(){
	ios::sync_with_stdio(false);
	cin >> n >> d;
	for(int i = 0; i < n; i++){
		cin >> p[i];
	}
	sort(p, p + n);  //前提是有序
	for(int i = 0; i < n; i++){  //多减1是因为找到的这个元素已经不满足小于d距离的条件了,所以它不属于朋友 
		sum += upper_bound(p, p + n, p[i] + d) - p - i - 1;			
	} 
	cout << sum << endl; 
	return 0;
} 

 


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326390837&siteId=291194637