20 pts
直接暴力枚举每一项,时间复杂度 。
40 pts
不难注意到,枚举到一定项数后一定会出现与前面某位相同的一项,而这一项到之前出现的那一项构成了循环,于是考虑用 unordered_map 来实现记录出现过的数以及对应的下标,如果当前数出现过,再计算循环节。(记得数组开到 左右,不然只有 30 pts,时间复杂度应和 ,, 的值域相关)
40pts
#include <bits/stdc++.h>
using namespace std;
#ifdef __linux__
#define gc getchar_unlocked
#define pc putchar_unlocked
#else
#define gc _getchar_nolock
#define pc _putchar_nolock
#endif
#define int long long
#define rint register int
#define R register
#define _ read<int>()
template<class T>inline T read()
{
R T r=0,f=1;R char c=gc();
while(!isdigit(c))
{
if(c=='-') f=-1;
c=gc();
}
while(isdigit(c)) r=(r<<1)+(r<<3)+(c^48),c=gc();
return f*r;
}
inline void out(rint x)
{
if(x<0) pc('-'),x=-x;
if(x<10) pc(x+'0');
else out(x/10),pc(x%10+'0');
}
const int N=1e8+10;
// unordered_map<int,int>c;
int c[N];
signed main()
{
rint t=_;
while(t--)
{
unordered_map<int,int>mp;
long long n=_,s=_,t=_,a=_,b=_,nn,p=-1;
c[0]=s;mp[s]=0;
for(rint i=1;i<=n;++i)
{
c[i]=c[i-1]+(c[i-1]<t?b:-a);
if(mp.find(c[i])!=mp.end())
{
nn=i-mp[c[i]],p=mp[c[i]];
break;
}
mp[c[i]]=i;
}
// cout<<nn<<' '<<p<<endl;
if(p!=-1) out(c[p+(n-p)%nn]);
else out(c[n]);
pc('\n');
mp.clear();
// c.clear();
}
return 0;
}正解
考虑正解,如果你写过暴力就容易发现,对于 需要判断 很麻烦,把 移过来,定义 此时只需判断 即可。
我们设一共加了 次 ,则共减掉了 次 ,则:
考虑如何快速处理出 ,观察上述代数式,不妨设 ,,则 ,显然 。
不难发现,引入任意一个整数 ,必然存在一个 使得 在 此区间长度为 ,于是我们考虑把 模后,选一个长度为 的连续区间代表,我们需要让两端代表落在此区间,即 移项可得:
即唯一存在的 。
则 。(建议使用 __int128)
时间复杂度 空间复杂度 。
Ac Code
#include <bits/stdc++.h>
using namespace std;
#ifdef __linux__
#define gc getchar_unlocked
#define pc putchar_unlocked
#else
#define gc _getchar_nolock
#define pc _putchar_nolock
#endif
#define int __int128
#define rint register int
#define R register
#define _ read<int>()
template<class T>inline T read()
{
R T r=0,f=1;R char c=gc();
while(!isdigit(c))
{
if(c=='-') f=-1;
c=gc();
}
while(isdigit(c)) r=(r<<1)+(r<<3)+(c^48),c=gc();
return f*r;
}
inline void out(rint x)
{
if(x<0) pc('-'),x=-x;
if(x<10) pc(x+'0');
else out(x/10),pc(x%10+'0');
}
const int N=1e8+10;
// unordered_map<int,int>c;
int c[N];
signed main()
{
rint t=_;
while(t--)
{
rint n=_,s=_,t=_,a=_,b=_;
rint x=s-t,M=a+b;
rint m=(n*a-x+b-1)/M;
out(x+m*M-n*a+t);pc('\n');
}
return 0;
}