8-3课程题目解析+总结
题目解析+总结
T639126
题意
有长度为的数组,请求出:
分析
暴力写法:
int sum = 0;
for(int i=1;i<=n;++i){
for(int j=i+1;j<=n;++j){
sum += (a[i] + a[j]) % 100000000;
}
}但是,因为数据量比较大,写暴力的话容易超时。 因此,我们需要进行进一步优化。
根据以上公式发现:每个数被相加了次,也就是说,就是所有的数的和乘长度减一的差,这种求和的问题就基本上完成了。 那怎样将多余的部分求出来呢? 这时候我们就可以使用二分了。对于每个数,求出比它们与的差大的数,加上cnt,最后就是多余的部分。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,sum = 0,cnt = 0,a[300005];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n;
for(int i=1;i<=n;++i) cin>>a[i];
sort(a+1,a+1+n);
for(int i=1;i<=n;++i){
sum += a[i] * (n-1);
cnt += n-(lower_bound(a+1+i,a+1+n,100000000-a[i]) - a)+1;
}
// cout<<cnt<<endl;
cout<<sum-cnt*100000000<<endl;
return 0;
}总结
排序 + 二分 + 公式推导
T638485【未作答】
题意
有种种类的卡片,面值为,已知每种种类的卡牌数量为无穷大,并且可以随便抽取牌数,得到总和,请问第小的是多少?
分析
我们可以使用搜索所来解这道题,但是我们需要一个优先队列按小顶堆存储数据。 首先将输入的数字存入到优先队列中,在搜索时选取一个最小的数,并遍历整个数组,每次都加上那个数(记得去重),并记录这是第几小。
int cnt = 0;
while(op.size()){
int top = op.top();
op.pop();
cnt++;
if(cnt == k){
cout<<top<<endl;
return 0;
}
for(int i=1;i<=n;++i){
if(!vis[a[i]+top]){
op.push(a[i]+top);
vis[a[i]+top] = 1;
}
}
}代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,k,a[11];
priority_queue<int,vector<int>,greater<int> >op;
map<int,bool>vis;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n>>k;
for(int i=1;i<=n;++i){
cin>>a[i];
if(!vis[a[i]]){
op.push(a[i]);
vis[a[i]] = 1;
}
}
int cnt = 0;
while(op.size()){
int top = op.top();
op.pop();
cnt++;
if(cnt == k){
cout<<top<<endl;
return 0;
}
for(int i=1;i<=n;++i){
if(!vis[a[i]+top]){
op.push(a[i]+top);
vis[a[i]+top] = 1;
}
}
}
return 0;
}总结
优先队列 + 搜索
U591734
题意
有一个迷宫,#表示障碍物,不能走动;.表示空地,如果这个格子的上下左右的任意一个是障碍,就不能走动了。请问,从一点出发,最多能走多少个格子?
分析
这里同样可以使用搜索来解决这道题。 我们把障碍物及障碍物周围的全部标记,也就是迷宫中的终点。随后,开始搜索,并记录这是第几个连通块。每次遍历结束后,都要来一次打擂台,最后输出打擂台的结果,就可以了。
代码
#include<bits/stdc++.h>
#define int long long
#define node pair<int,int>
using namespace std;
int vis[1001][1001];
char a[1001][1001];
int n,m,cnt,maxx = 1,color = 3;
int dx[] = {-1,1,0,0};
int dy[] = {0,0,-1,1};
void dfs(int x, int y) {
for (int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (xx<1||xx>n||yy<1||yy>m||vis[xx][yy]==color||a[xx][yy]=='#') continue;
vis[xx][yy]=color;
cnt++;
if (a[xx][yy]=='@') continue;
dfs(xx, yy);
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
cin>>a[i][j];
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
if(a[i][j] == '#') continue;
if(a[i-1][j] == '#' || a[i+1][j] == '#' || a[i][j-1] == '#' || a[i][j+1] == '#') a[i][j] = '@';
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
if(vis[i][j] == 0 && a[i][j] == '.'){
cnt = 1;
vis[i][j] = color;
dfs(i,j);
color++;
maxx = max(maxx,cnt);
}
}
}
cout<<maxx<<endl;
return 0;
}总结
找连通块 + 搜索 我也通过搜索拿分,可是没考虑到这是找连通块。