编程算法

版权声明:本文为博主原创文章,未经博主同意不得转载。

https://blog.csdn.net/u012515223/article/details/37909933

最好牛线(Best Cow Line) 代码(C)


本文地址: http://blog.csdn.net/caroline_wendy


题目: 给定长度为N的字符串S, 要构造一个长度为N的字符串T. 重复进行例如以下随意操作.

从S的头部删除一个字符, 放入T的尾部;

从S的尾部删除一个字符, 放入T的尾部;

目标是要构造字典序尽可能小的字符串T.


使用贪心算法, 不断选取S首尾最小的字符, 放入T, 假设相等, 则再次向内查找, 找到内部最小的.


代码:

/*
 * main.cpp
 *
 *  Created on: 2014.7.17
 *      Author: spike
 */

/*eclipse cdt, gcc 4.8.1*/

#include <stdio.h>
#include <limits.h>

#include <utility>
#include <queue>
#include <algorithm>

using namespace std;

class Program {
	static const int MAX_N = 10000;
	int N = 6;
	char S[MAX_N+1] = "ACDBCB";
public:
	void solve() {
		int a=0, b=N-1;
		while (a<=b) {
			bool left = false;
			for (int i=0; a+i<=b; i++) { //向内查找
				if(S[a+i] < S[b-i]) {
					left = true;
					break;
				} else if (S[a+i] > S[b-i]) {
					left = false;
					break;
				}
			}

			if (left) putchar(S[a++]);
			else putchar(S[b--]);
		}
		putchar('
');
	}
};


int main(void)
{
	Program P;
	P.solve();
    return 0;
}




输出:

ABCBCD









【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10815941.html