跳到正文

题解

题解:B4353 [信息与未来 2025] 程序套娃(暂无 SPJ)

wst000约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年7月11日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 5 分钟
获赞
2
题目
B4353

版本

  1. v1当前

思路

我们使用反推法,在反推的过程中找规律。我们设 n=8,k=109n=8,k=10^9(也是数据上限)。那么我们的 p7.cpp 是怎样的呢?

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
  cout<<1000000000;
  return 0;
}

现在我们要在 p6.cpp 中输出 p7.cpp。这也很简单。

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
  cout<<"#include<bits/stdc++.h>\nusing namespace std;int main(){cout<<\"1000000000\";return 0;}";
  return 0;
}

但我们注意到," 的前面加了一个 \。这是转义符,让系统可以正常输出像 ",\ 这样的特殊字符。

让我们继续。下面是 p5.cpp。

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
  cout<<"#include<bits/stdc++.h>\nusing
namespace std;int main(){cout<<\"#include<bits/std
c++.h>\\nusingnamespace std;
int main(){cout<<\\\"1000000000\\\";return 0;}\";
return 0;}";
  return 0;
}

(为了使大家能方便的查看,我在这里把一行拆成了许多行,这样是无法编译的)。

可以发现,我们又多加了一些 \。我们把原来属于 p7.cpp 的提出来。

C++
#include<bits/stdc++.h>
\\nusingnamespace std;
int main(){
  cout<<\\\"1000000000\\\";
  return 0;
}

为了使 p5.cpp 编译后变成 p6.cpp 的样子,所以我们使用转义符 \ 让系统认为这是一个字符串而不是有特殊意义的 \n。在第 4 行,我们加了 2 个 \ 。由于 \ 本来就是特殊字符,所以我们要用两个 \。现在我们还很难发现什么规律,我们继续。

下面是 p4.cpp。

C++
#include<bits/stdc++.h>
using namespace std;int main(){cout<<"#include<bits/stdc++.h>\nusing namespace std;int main(){cout<<\"#include<bits/stdc++.h>\\nusing namespace std;int main(){cout<<\\\"#include<bits/stdc++.h>\\\\nusing namespace std;int main(){cout<<\\\\\\\"1000000000\\\\\\\";return 0;}\\\";return 0;}\";return 0;}";
return 0;}

(工作量太大了,就不换行了。)

我们提取原来 p7.cpp 的部分。

C++
#include<bits/stdc++.h>
\\\\nusing namespace std;
int main(){
  cout<<\\\\\\\"1000000000\\\\\\\";
  return 0;
}

我们发现第 5 行的 \ 的数量(只算 " 号左边的,左右边数量一样)是 7,从 p7.cpp 到 p4.cpp 分别是 0,1,3,7。现在发现规律了吗?在py.cpp 中 px.cpp 双引号前的 \ 的数量是 2y−x−12^{y-x}-1 个,然后可以推出在p1.cpp 中,px.cpp 双引号前的 \ 共有 2x−1−12^{x-1}-1 个 \。但由于 \ 是特殊字符,在写程序时要 cout<<"\" 改成 cout<<"\\"。 (由于作者语文不好,有些东西没讲清楚,欢迎提问,代码自测正确,如错误欢迎提出)

code

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef const ll cll;
typedef vector<ll>vll;
typedef string str;
typedef pair<ll, ll>pll;
#define pb push_back
#define st first
#define nd second
cll llmi = -9187201950435737472;
cll llma = 9187201950435737471;
ll n,m;
void xg(ll x){/*输出x个\*/
	while(x--){
		printf("\\");
	}
}
void f(ll x){//x表示生成px.cpp
	if(x==n){printf("%lld",m);return;}
	if(x==1){
		printf("#include<bits/stdc++.h>\nusing namespace std;int main(){");
		printf("cout<<\"");
		f(x+1);
		printf("\";\nreturn 0;}");
	}
	else {
		printf("#include<bits/stdc++.h>");
		xg((1<<(x-2)));
		printf("nusing namespace std;");
		printf("int main(){");
		printf("cout<<");
		xg((1<<(x-1))-1);
		printf("\"");
		f(x+1);
		xg((1<<(x-1))-1);
		printf("\";return 0;}");
	}
}
int main() {
	scanf("%lld%lld",&n,&m);
	f(1);
	return 0;
}
原文
存档评论1 条抓取于