/*
环形字符串的最小字典序,2012年阅读四
输入
CBBADADA
输出
ACBBADAD
*/#include<bits/stdc++.h>
using namespace std;int n, ans;
string s;charget(int i){
//字符串围成了一个环 if(i < n)return s[i];elsereturn s[i - n];}intmain(){
cin >> s;
n = s.size();
ans =0;for(int i =1; i <= n -1; i ++){
for(int j =0; j <= n -1; j ++){
//以i为起始位置的字符串的字典序可能更小if(get(i + j)<get(ans + j)){
ans = i;break;}//以i为起始位置的字符串的字典序太大 elseif(get(i + j)>get(ans + j)){
break;}}}for(int j =0; j <= n -1; j ++) cout <<get(ans + j);
cout << endl;return0;}
双指针算法
/*
字符串的逆序,2007年完善一
*/#include<bits/stdc++.h>
using namespace std;voidreverse(char s[]){
for(int i =0, j =strlen(s)-1; i < j; i ++, j --){
swap(s[i], s[j]);}}intmain(){
char line[100];
cin >> line;reverse(line);
cout << line;return0;}
递推与递归
/*
转成递推,2010年阅读四
*/#include<bits/stdc++.h>#defineNUM5
using namespace std;intr(int n){
if(n <= NUM)return n;for(int i =1; i <= NUM; i ++){
if(r(n - i)<0){
return i;}}return-1;}intmain(){
int n;scanf("%d",&n);printf("%d\n",r(n));return0;}
/*
转成递推,2011年阅读四
输入
7 4
输出
20
*/#include<bits/stdc++.h>
using namespace std;intsolve(int n,int m){
if(m ==1)return1;int sum =0;for(int i =1; i < n; i ++) sum +=solve(i, m -1);return sum;}intmain(){
int n, m;
cin >> n >> m;
cout <<solve(n, m)<< endl;return0;}
搜索与回溯算法
/*
国王放置,2009年完善二
在n*m的棋盘上放置k个国王,要求k个国王互相不攻击,有多少种不同的放置方法。
假设国王放置在第(x,y)格,国王的攻击的区域是:
(x-1,y-1),(x-1,y),(x-1,y+1),
(x,y-1),(x,y+1),
(x+1,y-1),(x+1,y),(x+1,y+1)。
读入三个数n, m, k,输出答案。
题目利用回溯法求解。
棋盘行标号为0 ~ n-1,列标号为0 ~ m-1。
*/#include<bits/stdc++.h>
using namespace std;int n, m, k, ans;int h[10][10];voiddfs(int x,int y,int cnt){
if(cnt == k){
ans ++;return;}while(true){
if(!h[x][y]){
//标记周围的八个位置for(int i = x -1; i <= x +1; i ++){
for(int j = y -1; j <= y +1; j ++){
if(i <0|| i > n || j <0|| j > m)continue;
h[i][j]++;}}//搜索 dfs(x, y, cnt +1);//回溯,取消周围八个位置的标记 for(int i = x -1; i <= x +1; i ++){
for(int j = y -1; j <= y +1; j ++){
if(i <0|| i > n || j <0|| j > m)continue;
h[i][j]--;}}}
y ++;if(y == m) x ++, y =0;if(x == n)break;}}intmain(){
cin >> n >> m >> k;dfs(0,0,0);
cout << ans;return0;}