大家好!
不定时更新,题目+解析+评测结果+完整程序,有问题有瑕疵欢迎评论区留言!
1.题目
1. K12275 约瑟夫问题
题目描述
N个人围成一圈,从第一个开始报数,数到M的人出队,然后他的下一位继续从1开始报数,数到M的出队,如此循环直到剩下一个人,求最后剩下的那个人最初是队伍中的第几位。
输入格式
输入玩家人数 N,输入报到哪个数(M)会被淘汰 (M<N,N<100,M,N都是正整数)
输出格式
输出被淘汰人的顺序,以及最终胜利的人(换行输出)
输入输出样例
输入样例1:复制
5 3
输出样例1:复制
the 3 boy out
the 1 boy out
the 5 boy out
the 2 boy out
the 4 boy win
【耗时限制】1000ms 【内存限制】128MB
2.解析
这是一道十分经典的问题。
1.变量
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
}
n:玩家人数。
m:报到哪个数会被淘汰。
now:当前这个人是第几位。
f[]:标记这位玩家是否被淘汰了(false:没淘汰|true:淘汰了)。
2.输入
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
scanf("%lld %lld",&n,&m);
}
直接输入n和m。
3.动态规划
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
scanf("%lld %lld",&n,&m);
for(int i=1;i<=n;i++){
int cnt=0;
while(cnt<m){
now++;
if(now==n+1) now=1;
if(!f[now]) cnt++;
}
}
}
cnt:报的数。
4. 标记
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
scanf("%lld %lld",&n,&m);
for(int i=1;i<=n;i++){
int cnt=0;
while(cnt<m){
now++;
if(now==n+1) now=1;
if(!f[now]) cnt++;
}
f[now]=true;
}
}
实时标记淘汰情况。
4.判断输出
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
scanf("%lld %lld",&n,&m);
for(int i=1;i<=n;i++){
int cnt=0;
while(cnt<m){
now++;
if(now==n+1) now=1;
if(!f[now]) cnt++;
}
f[now]=true;
if(i<n) printf("the %lld boy out\n",now);
else printf("the %lld boy win\n",now);
}
}
判断输出。
3.评测结果
4.完整程序
#include <bits/stdc++.h>
using namespace std;
int n,k,a[1001];
int fun(string x){
int sum = 0;
while(x){
string
sum+=x%10;
x/=10;
}
return sum;
}
bool cmp(const int x,const int y){
if(fun(x)!=fun(y)) return fun(x)>fun(y);
return x>y;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++){
cin>>a[i];
}
k=a[1];
sort(a+1,a+n+1,cmp);
int pm=0;a[n+1]=-1;
for(int i=1;i<=n;i++){
if(a[i]!=a[i+1]){
pm++;
if(a[i]==k){
cout<<pm;
return 0;
}
}
}
return 0;
}
谢谢大家,给个赞呗!💕💕💕