牛客第三场E题(存一下大数模板)
这题之前用python一直re,后来才知道递归爆栈了
c++题解
#include<bits/stdc++.h>
#define ll long long
#define pii pair<int, int>
using namespace std;
typedef vector<int> VI;
const int N = 1e5+10;
int a[N];
int v[N];
namespace bigI
{
const int bas = 1e4; // 压位优化 1位代表四位十进制
void print(VI A)
{
if (A.size() == 0)
return;
printf("%d", A.back()); // uncheck A is empty
for (int i = A.size() - 2; i >= 0; --i)
printf("%04d", A[i]); // 长度为每一位代表的长度
puts(""); // 换行
}
// 整数加法就先用大数1成 转成大数加
VI add(VI A, VI B)
{
static VI C;
C.clear();
for (int i = 0, t = 0; i < (int)A.size() || i < (int)B.size() || t; ++i)
{
if (i < (int)A.size())
t += A[i];
if (i < (int)B.size())
t += B[i];
C.push_back(t % bas);
t /= bas;
}
return C;
}
VI mul(VI A, ll b)
{
static VI C;
C.clear();
ll t = 0;
for (int i = 0; i < (int)A.size() || t; ++i)
{
if (i < (int)A.size())
t += A[i] * b;
C.push_back(t % bas);
t /= bas;
}
return C;
}
// 自己写的 可能有错
VI div(VI A, ll B)
{
static VI C;
C.clear();
for (int i = (int)A.size() - 1, r = 0; i >= 0; --i)
{
r = r * bas + A[i];
C.push_back(r / B);
r %= B;
}
reverse(C.begin(), C.end());
while ((int)C.size() > 1 && !C.back())
C.pop_back();
return C;
}
} // namespace bigI
int dfs(int p) {
if (v[p])
return 0;
v[p] = 1;
return dfs(a[p]) + 1;
}
int b[N],num[N];
int main(){
int n;
cin >> n;
for (int i = 1; i <= n;++i)
{
cin >> a[i];
}
vector<int> lens;
for (int i = 1; i <= n;++i) {
if(v[i])
continue;
int l = dfs(i);
// cerr << l << '
';
lens.push_back(l);
}
for(auto i:lens){
int x = i,sum=0;
for(int j=2;j*j<=x;j++){
sum=0;
while(x%j==0){
sum++;
x = x / j;
}
num[j] = max(num[j],sum);
}
if(x > 1)
num[x] = max(num[x],1);
}
VI ans = {1};
for(int i=2;i<=n;i++){
while(num[i] > 0){
ans = bigI::mul(ans, i);
num[i]--;
}
}
bigI::print(ans);
return 0;
}
py迭代题解
import math as ma
v = []
a = []
n = int(input())
a = [0] + list(map(int,input().split()))
for i in range(0,100000):
v.append(0)
v.append(0)
len = []
for i in range(1,n+1):
if v[i] == 1:
continue
temp = 0
j = i
while v[j] == 0:
temp += 1
v[j] = 1
j = a[j]
len.append(temp)
ans = 1
for i in len:
ans = ans * i // ma.gcd(i,ans)
print(ans)
py迭代题解
import math as ma
import sys
sys.setrecursionlimit(100005)//手动开栈
v = []
a = []
def dfs(p):
if v[p] == 1:
return 0
v[p] = 1
return (dfs(a[p]) + 1)
a.append(0)
n = int(input())
temp = list(map(int,input().split()))
for i in temp:
a.append(i)
# print(a)
for i in range(1,2*n):
v.append(0)
v.append(0)
len = []
for i in range(1,n+1):
if v[i] == 1:
continue
l = dfs(i)
len.append(l)
ans = 1
for i in len:
ans = ans * i // ma.gcd(i,ans)
print(int(ans))