A代码填充--谁挡住了我
时间: 1ms 内存:128M
描述:
n个人前后站成一列,对于队列中的任意一个人,如果排在他前面的人的身高大于等于他的身高,则称该人被挡住了。小明是队列中的一员,问有多少人挡住了他?
注:本题只需要提交填写部分的代码,请按照C++方式提交。
#include <iostream>
using namespace std;
struct Node
{
float height;
Node *next;
};
Node *creatlist(int n)
{
Node *t=new Node;
cin>>t->height;
if(n>1)
t->next = creatlist(n-1);
else
t->next = NULL;
return t;
}
Node *findlist(Node *head,int n)
{
if(n<1||!head)
return NULL;
if(n==1)
return head;
return findlist(head->next,n-1);
}
int countlist(Node *head,Node *p)
{
if(!head||!p||head==p)
return 0;
/*
请在该部分补充缺少的代码
*/
}
int main(void)
{
int n,pos;
Node *head,*xiaoming;
cin>>n; //人数
head = creatlist(n);
cin>>pos; //小明的序号
xiaoming = findlist(head,pos);
cout<<countlist(head,xiaoming)<<endl;
return 0;
}
输入:
第一行 n
第二行 n个人的身高
第三行 小明从前往后数的序号
输出:
挡住小明的人数
示例输入:
10
1.86 1.74 1.67 1.87 1.68 1.9 1.65 1.65 1.68 1.65
8
示例输出:
7
提示:
参考答案(内存最优[1092]):
#include <stdio.h>
int main()
{
int m,n,i,j,sum=0;
float a[10000];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
scanf("%d",&m);
for(i=0;i<m-1;i++)
{
if(a[i]>=a[m-1])
sum++;
}
printf("%d",sum);
}
参考答案(时间最优[0]):
#include <iostream>
using namespace std;
struct Node
{
float height;
Node *next;
};
Node *creatlist(int n)
{
Node *t=new Node;
cin>>t->height;
if(n>1)
t->next = creatlist(n-1);
else
t->next = NULL;
return t;
}
Node *findlist(Node *head,int n)
{
if(n<1||!head)
return NULL;
if(n==1)
return head;
return findlist(head->next,n-1);
}
int countlist(Node *head,Node *p)
{
if(!head||!p||head==p)
return 0;
int num=(head->height>=p->height);
return num+countlist(head->next,p);
}
int main(void)
{
int n,pos;
Node *head,*xiaoming;
cin>>n; //人数
head = creatlist(n);
cin>>pos; //小明的序号
xiaoming = findlist(head,pos);
cout<<countlist(head,xiaoming)<<endl;
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。