这是题目:
选村长
(时间限制:1000ms 内存限制:65536KB
描述
青青草原的羊村村长换届,现有三位候选羊:
输入喜羊羊,懒羊羊和美羊羊,他们的编号分别为1、2、3,另有n位投票羊进行投票,请将投票后的三位候选羊,按照票数降序排列,若票数相同,则编号小的靠前。
使用结构体及sort排序
共有两行,第一行为一个大于0的整数n,表示有n位羊参与投票。 第二行包括n个范围在1至3之间的整数,表示这n位羊的投票编号。(假设没有投票羊弃权)
输出
三行,每行展示一位按照票数排序后的羊的的信息,包括候选羊编号,姓名以及票数。
输入示例
10
3 2 1 3 2 1 3 2 1 3
输出示例
3 美羊羊 4
1 喜羊羊 3
2 懒羊羊 3
我的c++代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct cz{
int b,p;
string name;
};
bool cmp(cz a,cz b){
if(a.p==b.p){
cout<<11<<endl;
return a.b<b.b;
}
else{
cout<<22<<endl;
return a.p<a.p;
}
}
int main(){
int n=0,xp;
cz a[3];
cin>>n;
a[0].name="喜羊羊";
a[0].b=1;
a[1].name="懒羊羊";
a[1].b=2;
a[2].name="美羊羊";
a[2].b=3;
for(int i=1;i<=n;i++){
cin>>xp;
cout<<xp<<endl;
if(xp==1){
a[0].p++;
}
if(xp==2){
a[1].p++;
}
if(xp==3){
a[2].p++;
}
}
a[2].p++;
sort(a,a+3,cmp);
for(int i=0;i<3;i++){
cout<<a[i].b<<" "<<a[i].name<<" "<<a[i].p<<endl;
}
return 0;
}
1.return a.p < a.p; -> return a.p > b.p;
2. a[2].p++; //去掉
sort(a,a+3,cmp);
3.添加
a[0].p=0;
a[1].p=0;
a[2].p=0;
///////代码
#include<iostream>
#include<algorithm>
using namespace std;
struct cz{
int b,p;
string name;
};
bool cmp(cz a,cz b){
if(a.p==b.p){
cout<<11<<endl;
return a.b<b.b;
}
else{
cout<<22<<endl;
return a.p>b.p;
}
}
int main(){
int n=0,xp;
cz a[3];
cin>>n;
a[0].name="喜羊羊";
a[0].b=1;
a[0].p=0;
a[1].name="懒羊羊";
a[1].b=2;
a[1].p=0;
a[2].name="美羊羊";
a[2].b=3;
a[2].p=0;
for(int i=1;i<=n;i++){
cin>>xp;
cout<<xp<<endl;
if(xp==1){
a[0].p++;
}
if(xp==2){
a[1].p++;
}
if(xp==3){
a[2].p++;
}
}
sort(a,a+3,cmp);
for(int i=0;i<3;i++){
cout<<a[i].b<<" "<<a[i].name<<" "<<a[i].p<<endl;
}
return 0;
}
1.结构体内的p没有初始化,所以后面再p++是没用的
2.cmp函数判断有误,要按照票数降序排列
3.有多余的cout语句
#include<iostream>
#include<algorithm>
#include <string>
using namespace std;
struct cz{
int b, p=0;
string name;
};
bool cmp(cz a, cz b){
if (a.p == b.p){
return a.b<b.b;
}
else{
return a.p>b.p;
}
}
int main(){
int n = 0, xp;
cz a[3];
cin >> n;
a[0].name = "喜羊羊";
a[0].b = 1;
a[1].name = "懒羊羊";
a[1].b = 2;
a[2].name = "美羊羊";
a[2].b = 3;
for (int i = 0; i < n; i++){
cin >> xp;
//cout << xp << endl;
if (xp == 1){
a[0].p++;
}
if (xp == 2){
a[1].p++;
}
if (xp == 3){
a[2].p++;
}
}
sort(a, a + 3, cmp);
for (int i = 0; i<3; i++){
cout << a[i].b << " " << a[i].name << " " << a[i].p << endl;
}
system("pause");
return 0;
}