程序设计思维与实践 Week12 作业 (3/4/数据班)
A - 必做题 - 1
问题分析
数字存放在map<int,int>
中,关键字是输入的数字,值是出现的次数。然后统计次数即可。
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
int a;
map<int, int> mp;
while(cin>>n){
mp.clear();
for(int i=0;i<n;++i){
cin>>a;
mp[a]++;
}
int ans=0;
int num=0;
for(auto&i:mp){
if(num<i.second){
num=i.second;
ans=i.first;
}
if(num>=(n+1)/2){
break;
}
}
cout<<ans<<endl;
}
return 0;
}
B - 必做题 - 2
问题分析
bfs问题,只不过这次是三维的,有六个移动方向。
// #include<bits/stdc++.h>
// using namespace std;
#include<iostream>
#include<queue>
#include <string>
using namespace std;
char maze[35][35][35];
bool inq[35][35][35];
int L,R,C;
struct node
{
int x,y,z;
int step;
}S,E,Node;
bool check(int z,int y,int x){
if(x>=C||x<0||y>=R||y<0||z>=L||z<0){
return false;
}
if(inq[z][y][x]==true||maze[z][y][x]=='#'){
return false;
}
return true;
}
int dx[6]={0,0,-1,1,0,0};
int dy[6]={0,0,0,0,1,-1};
int dz[6]={1,-1,0,0,0,0};
int bfs(){
queue<node> q;
q.push(S);
while(!q.empty()){
node top=q.front();
q.pop();
if(top.x==E.x&&top.y==E.y&&top.z==E.z){
return top.step;
}
for(int i=0;i<6;++i){
int newx=top.x+dx[i];
int newy=top.y+dy[i];
int newz=top.z+dz[i];
if(check(newz,newy,newx)){
Node.x=newx;
Node.y=newy;
Node.z=newz;
Node.step=top.step+1;
q.push(Node);
inq[newz][newy][newx]=true;
}
}
}
return -1;
}
int main(){
int l,r,c;
while(cin>>l>>r>>c){
for(int i=0;i<35;++i){
for(int j=0;j<35;++j){
for(int k=0;k<35;++k){
inq[i][j][k]=false;
}
}
}
if(l==0&&r==0&&c==0){
break;
}
L=l;R=r;C=c;
string s;
for(int i=0;i<l;++i){
for(int j=0;j<r;++j){
cin>>s;
int k=0;
// for(auto&p:s){
// if(p=='E'){
// E.z=i;
// E.y=j;
// E.x=k;
// }
// else if(p=='S'){
// S.z=i;
// S.y=j;
// S.x=k;
// }
// maze[i][j][k++]=p;
// }
for(int ths=0;ths<s.length();++ths){
char p=s[ths];
if(p=='E'){
E.z=i;
E.y=j;
E.x=k;
}
else if(p=='S'){
S.z=i;
S.y=j;
S.x=k;
}
maze[i][j][k++]=p;
}
}
}
S.step=0;
int ans=bfs();
if(ans==-1){
cout<<"Trapped!"<<endl;
}
else{
cout<<"Escaped in "<<ans<<" minute(s)."<<endl;
}
}
return 0;
}
C - 必做题 - 3
问题分析
找不重叠的区间,使得和为最大值。
#include<bits/stdc++.h>
using namespace std;
const int INF=1e9;
const int mx_n=1e6+5;
int f[mx_n],pre[mx_n];
int main(){
int m,n;
while(scanf("%d%d",&m,&n)!=EOF){
fill(f,f+mx_n,0);
fill(pre,pre+mx_n,0);
int *a=new int[n+1];
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
int ans;
for(int i=1;i<=m;i++){
ans=0-INF;
for(int j=i;j<=n;j++){
f[j]=max(f[j-1],pre[j-1])+a[j];
pre[j-1]=ans;
if(f[j]>ans){
ans=f[j];
}
}
}
cout<<ans<<endl;
delete[]a;
}
return 0;
}