C++——do while应用

13 篇文章 0 订阅

C++——do while应用

移动问题:有一行数据,左边有n个1,右边有n个2,1和2相邻可以交换,至无连续的1相邻为止。显示移动过程。
这个问题一开始认为用递归应该没有问题,程序如下:

#include <iostream>
#include<deque>
#include<time.h>
using namespace std;
void dfs(string s);
deque <string> result;
string source, target;
time_t start_time;
int n;

void dfs(string state) {
    if (state == target) {
        for (auto k : result) cout << k << endl;
        cout << "共移动" << result.size() - 1 << "步,耗时" << (double)(clock() - start_time) / CLOCKS_PER_SEC << "秒。" << endl;
        exit(0);
    }
    for (int i = 0; i < 2 * n-1; i++) {
        if (state[i]=='1' && state[i + 1]=='2') {
            swap(state[i], state[i + 1]);
            result.push_back(state);
            dfs(state);
            swap(state[i], state[i + 1]);
            result.pop_back();
        }
    }
}

int main() {
    cout << "请输入一个不小于2的整数:" << endl;
    cin >> n;
    start_time = clock();
    for (int i = 0; i < 2 * n; i++) {
        source += (i < n) ? '1' : '2';
        target += (i %2==0) ? '1' : '2';
    }
    result.push_back(source);
    dfs(source);
}

但当n超过4后,等待的时间太长,显然程序的适应性很差,还是找规律进行直接交换来得快。这个规律读者一看就知道,就不细说了。在这里用到do while语句,程序的结构很清晰。
程序代码如下,结果就不展示了。

#include <iostream>
#include<time.h>
using namespace std;
string state;
time_t start_time;
int n;

int main() {
	cout << "请输入一个不小于2的整数:" << endl;
	cin >> n;
	if (n < 2) {
		cout << "输入错误!" << endl;
		return 0;
	}
	start_time = clock();
	for (int i = 0; i < 2 * n; i++) state += (i < n) ? '1' : '2';
	cout << state << endl;
	int k = n - 1, count = 0;
	do {
		for (int i = k; i < 2 * k; i++) {
			swap(state[i], state[i + 1]);
			cout << state << endl;
			count++;
		}
	} while (k--);
	cout << "共移动" << count << "步,耗时" << (double)(clock() - start_time) / CLOCKS_PER_SEC << "秒。" << endl;
	return 0;
}

当然用for循环是最简单的,代码可以精简很多:

#include <iostream>
#include<time.h>
using namespace std;

int main() {
	string state;
	int n;
	cout << "请输入一个不小于2的整数:" << endl;
	cin >> n;
	if (n < 2) {
		cout << "输入错误!" << endl;
		return 0;
	}
	time_t start_time = clock();
	for (int i = 0; i < 2 * n; i++) state += (i < n) ? '1' : '2';
	cout << state << endl;
	for (int i = n - 1; i > 0; i--) 
		for (int j = i; j < 2 * i; j++) {
			swap(state[j], state[j + 1]);
			cout << state << endl;
		}
	cout << "共移动" << n*(n-1)/2 << "步,耗时" << (double)(clock() - start_time) / CLOCKS_PER_SEC << "秒。" << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值