- 汉诺塔问题 move 1 from A to B
- 2024-08-05 23:25:21 @
#include<bits/stdc++.h>
using namespace std;
int n,now[50],la[50],cnt;string pan="0ABC";
void move(int x,int y)
{
if(now[x]==y)return;
for(int i=x-1;i>=1;i--)
move(i,6-(now[x]+y));
printf("move %d from %c to %c\n",x,pan[now[x]],pan[y]);
now[x]=y,cnt++;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
//ios::sync_with_stdio(false);
/*
只能用freopen看出来
加了ios::sync_with_stdio(false);
ans:
7
move 1 from A to B
move 2 from A to C
move 1 from B to C
move 3 from A to B
move 1 from C to B
move 2 from C to A
move 1 from B to C
不加
ans:
move 1 from A to B
move 2 from A to C
move 1 from B to C
move 3 from A to B
move 1 from C to B
move 2 from C to A
move 1 from B to C
7
????
*/
cin>>n;
for(int i=1;i<=3;i++)
{
int p;cin>>p;
for(int j=1;j<=p;j++)
{
int a;cin>>a;
now[a]=i;
}
}
for(int i=1;i<=3;i++)
{
int p;cin>>p;
for(int j=1;j<=p;j++)
{
int a;cin>>a;
la[a]=i;
}
}
for(int i=n;i>=1;i--)
move(i,la[i]);
cout<<cnt<<endl;
return 0;
}
2 条评论
-
240803gj徐嘉昊 (2212224徐嘉昊) LV 10 @ 2025-08-17 21:01:42
警示后人!!! 时隔一年,现在我可以具体的说是咋回事了。起因是这样的,由于大坤的代码耗时了5s多,因此我尝试着把我的scanf和printf改成cin和cout看看是不是这么一回事,并且开了取消同步(即本讨论的标题那一段代码),但是我仍然使用了puts("0"),最终无情的测评机给我判了wa(qwq)。我询问了百度,知道了这是咋回事,一下是百度的原话,的精简版: 当你取消这种同步(通过调用std::ios_base::sync_with_stdio(false)),你就告诉C++标准库不再自动同步其C++风格的输入输出流与C风格的输入输出流。这意味着,如果你在取消同步后继续使用C风格的输入输出函数(如printf, scanf, puts, gets等),而没有正确地刷新或处理C++风格的流(如使用std::flush或在C++风格流后调用std::endl),可能会导致数据不一致或未定义的行为。 翻译成人话就是取消同步刷新了流的风格,导致两者不兼容,最终出错。但是百度也给出了折中的办法: 刷新流:在调用C风格函数之前,确保刷新C++风格的流。例如,使用std::cout << std::flush;或者std::cout << std::endl;来确保所有缓冲的数据都被发送到输出设备。 但是这可能有点麻烦,总之要确保两者不能混用!!! Last but not least.咱来解决本讨论的问题,由于楼主在代码中取消了同步,但又同时使用了printf输出,导致c++流和c流不同步,最终导致出错。 完结撒花( ̄▽ ̄)~*
-
2024-08-06 16:31:01@
是关于printf和cout的问题,但我不知道具体怎么说
- 1
信息
- ID
- 1548
- 难度
- 6
- 分类
- (无)
- 标签
- 递交数
- 28
- 已通过
- 10
- 通过率
- 36%
- 被复制
- 2
- 上传者