java - 调试 SPOJ STPAR 的 java 代码
问题描述
我正在尝试在 SPOJ http://www.spoj.com/problems/STPAR/上解决这个问题
我的代码写在以下链接中: 我的解决方案
这是我的代码
public static void main(String[] args)throws IOException
{
Scan sc = new Scan();
PrintWriter pr = new PrintWriter(System.out);
while(true)
{
int n = sc.scanInt();
if(n == 0)
break;
ArrayStack<Integer> stack = new ArrayStack<>();
int[] arr = new int[n+1];
arr[0] = -1;
// without using an extra array
// for(int i=0; i<n; i++)
// arr[i+1] = sc.scanInt();
boolean isOrdered = true;
int count = 1, number;
for(int i=0; i<n; i++)
{
// System.out.println("i: " + i + " n: " +n + " count: " + count);
// number = arr[i+1];
number = sc.scanInt();
while(stack.peep() != null && stack.peep() == count)
{
// pr.print(stack.pop() + " ");
// System.out.println("From 2");
stack.pop();
count++;
}
if(number == count)
{
// System.out.println("From 1");
count++;
}
else
{
if(stack.peep() == null || stack.peep() > number)
{
// System.out.println("From 3");
stack.push(number);
}
else if(stack.peep() <= number)
{
// System.out.println("From 4");
isOrdered = false;
// break;
}
}
// else
// pr.println("From 5");
// System.out.println("stack: " + stack.toString());
}
// pr.println();
if(isOrdered)
pr.println("yes");
else
pr.println("no");
}
sc.close();
pr.close();
}
我已经看到了关于这个问题的所有评论。所有提到的测试用例都通过了我的代码,但提交后它仍然给了 NZEC。我还在互联网上搜索了解决方案,其中大多数看起来像我的解决方案。在尝试解决超过 2 小时后,我发布了这个问题。请帮助我调试我的代码。
对不起,如果它看起来很幼稚!
解决方案
This is my solution to the question:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n!=0)
{
int arr[]=new int[n], k=1;
for(int i=0; i<n; i++)
arr[i]=sc.nextInt();
int stack[]=new int[n], top=-1, i=0;
Arrays.fill(stack, 0);
while(i<n)
{
if(arr[i]!=k)
{
if(top<0)
{
top=top+1;
stack[top]=arr[i];
i++;
}
else if(stack[top]==k)
{
top--;
k++;
}
else
{
top=top+1;
stack[top]=arr[i];
i++;
}
}
else
{
k++;
i++;
}
}
for(i=top; i>=0; i--, k++)
if(stack[i]!=k)
break;
if(k==n+1)
System.out.println("yes");
else
System.out.println("no");
n=sc.nextInt();
}
}
}
推荐阅读
- reactjs - 在 React 项目中使用 Material ui 和 Tailwind css
- linux - 从 USB 设备加载根文件系统
- java - 如何转换 AWS Lambda 为 AWS Batch 创建图像
- javascript - 如何在使用 JavaScript 检测选项卡更改时获取选项卡的标题/URL
- r - 使用 R 从 vobjtovarid4 读取 netCDF 文件时出错
- azure - 如何在 ADF 的复制活动中使“表格选项”动态化?
- android - 华为映射在渲染时抛出数组越界异常
- php - Orchid\Screen\Sight::buildDd() 的返回值必须是 string 类型或 null
- java - 从 Postman 请求 Spring Boot 中读取 Basic Authorization 的用户名和密码值
- html - SVG 图像未在 IOS 设备上加载