题意
圆形球场有n个门,Allen想要进去看比赛。Allen采取以下方案进入球场:开始Allen站在第一个门,如果当前门前面有人Allen会花费单位时间走到下一个门,如果没人Allen从这个门就进去了。球场的每个门,每单位时间可以进去一个人。问Allen最终是从哪个门进入球场的?
思路
开始的时候,我直接用模拟写的,果断TLE。
TLE如下:
#include<bits/stdc++.h>
#define sf scanf
#define pf printf
#define maxn 300010
using namespace std;
int n,A[maxn],tmp;
int main(){
cin>>n;
for(int i=0;i<n;i++)
cin>>A[i];
//模拟
int cur=0;
int t=A[cur];
while(1){
tmp=A[cur];
if(cur>=n){
cur=0;
for(int i=0;i<n;i++){
if(A[i]-n>0) A[i]-=n;
else A[i]=0;
}
}
//在一次访问中的操作
else{
if(A[cur]-cur<=0){
cout<<cur+1<<endl;
break;
}
else {
tmp-=cur;
}
cur++;
}
}
return 0;
}
参考别人的代码:
我们可以发现是有规律的。我们假设第i个门有a个人,Allen第x圈可以从此进入,那么有:x∗n+i=a→x=abs(a−i)/n,所以第一个最小圈数进入的那个门就是答案。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5+5;
const int INF = 0x3f3f3f3f;
int n, ans;
int main()
{
scanf("%d", &n);
int MIN = INF;
for (int i = 1; i <= n; i++)
{
int a; scanf("%d", &a);
if(MIN > (a-i+n)/n)//x*n+i=a =》x=abs(a-i)/n
{
MIN = (a-i+n)/n;
ans = i;
}
}
printf("%d\n", ans);
return 0;
}
/*
4
2 3 2 0
*/