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;
}