uva 110(回溯)

题意:根据样例中的格式,写出从1到n的所有判断大小的过程和结果。

题解:解决问题有两个,第一个是n个数的大小排列顺序,另一个是if - then - else 的添加。

先考虑第一个问题,排列顺序是首先让一个字符串存入 a,然后插入b,顺序是从后向前插入,即 a b 和 b a ,然后添加c,同样是从后向前,顺序是 a b c 、 a c b 、 c a b 、b a c 、b c a 、c b a ,之后的依次类推。这种添加方法需要用递归的方法实现,可以调用string中的Insert(int pos, string s)(第一个参数是位置,第二个参数是添加的字符串)添加字符,注意每次递归后要把字符串恢复成之前的样子,用string中的erase(int pos, int num)(第一个参数是位置,第二个参数是删除字符个数)函数来删除添加的字符,这里运用了回溯的思想,然后如果长度达到了n输出就可以了。

第二个问题,if-then-else 的情况有三种,可以找到一个规律,如果在开头添加字符时,用的是单独的else,如果是尾部添加字符时,用的是 if () then,其他添加情况用的是 else if () then ,所以在插入函数调用结束后就可以输出相应的if - then - else,括号里填的是添加的位置的前一个字符和当前字符。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;

string str; 
int n;

void dfs (int a, string s) {
	if (a == n)	{
		cout << "writeln(" << s[0];
		for (int i = 1; i < s.size(); i++)
			cout << "," << s[i];
		cout <<  ")\n";
		return;
	}
	for (int i = a; i >= 0; i--) {
		string temp = "";
		temp += ('a' + s.size());
		s.insert(i, temp);
		if (i != a && i != 0)
			cout << "else if " << s[i - 1] << " < " << s[i] << " then\n";
		if (i == a)
			cout << "if " << s[s.size() - 2] << " < " << s[s.size() - 1] << " then\n";
		if (i == 0)
			cout << "else\n";
		dfs(a + 1, s);
		s.erase(i, 1);
	}
}

void solve () {
	cout << "readln(a";
	for (int i = 1; i < n; i++)
		cout << "," << (char)(i + 'a');
	cout << ");" << endl;
	dfs(1, "a");
}

int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		scanf("%d", &n);
		cout << "program sort(input,output);" << endl << "var" << endl << "a";
		for (int i = 1; i < n; i++)
			cout << "," << (char)(i + 'a');
		cout << " : integer;" << endl << "begin" << endl;
		solve();
		cout << "end." << endl;
		if (t)
			cout << endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值