题解:P14159 [ICPC 2022 Nanjing R] 邪恶铭刻
elephant1881 · · 题解
此题对于
我们可以发现,
通分得
因为
而
通分得
该式一定为正。
结论:
综上,写出以下代码:
#include<bits/stdc++.h>
using namespace std;
int a[1000010];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int sum=1,cnt=1;
bool f=1;
for(int i=1;i<=n;i++){
if(a[i]==1) cnt++,sum++;
else if(a[i]==-1){
if(cnt>=2) cnt--;
else{
cout<<-1<<'\n';
f=0;
break;
}
}else{
if(cnt<2) cnt++,sum++;
else cnt--;
}
}
if(f){
int gcd=__gcd(cnt,sum);
cout<<sum/gcd<<" "<<cnt/gcd<<'\n';
}
}
return 0;
}
测样例发现
4
1 0 -1 0
这组数据输出为
-1
但答案为
3 1
这个数据 Wrong Answer 了。因为第一个
出现这种情况应该修改
AC代码如下:
#include<bits/stdc++.h>
using namespace std;
int a[1000010];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int sum=1,cnt=1,k=0;
bool f=1;
for(int i=1;i<=n;i++){
if(a[i]==1) cnt++,sum++;
else if(a[i]==-1){
if(cnt>=2) cnt--;
else if(k>=1) k--,sum++,cnt++;
else{
cout<<-1<<'\n';
f=0;
break;
}
}else{
if(cnt<2) cnt++,sum++;
else cnt--,k++;
}
}
if(f){
int gcd=__gcd(cnt,sum);
cout<<sum/gcd<<" "<<cnt/gcd<<'\n';
}
}
return 0;
}
如果您喜欢本篇题解,请顺手点个赞,谢谢!