一、交换矩阵的行
#include <iostream>
using namespace std;
const int MAX_SIZE = 101;
int mat[MAX_SIZE][MAX_SIZE],n,m,max_sum,row;
int main() {
m = 3,n=4;
max_sum = -2147483648;
for(int i = 1;i <= m;++i){
for(int j = 1;j <= n;++j){
mat[i][j] = i*j;
}
}
for(int i = 1;i <= m;++i){
for(int j = 1;j <= n;++j){
mat[i][0] += mat[i][j];
}
if(max_sum < mat[i][0]){
max_sum = mat[i][0];
row = i;
}
}
swap(mat[1],mat[row]);
for(int i = 1;i <= m;++i){
for(int j = 1;j <= n;++j){
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
二、指针访问数组
#include<iostream>
using namespace std;
const int ROW_SIZE = 101,COL_SIZE = 101;
int mat[ROW_SIZE][COL_SIZE],upper_sum,lower_sum,diognal_sum;
int (*pInt)[101];
int main(){
for(int i = 0;i < ROW_SIZE;++i){
for(int j = 0;j < COL_SIZE;++j){
cin >> mat[i][j];
}
}
for(auto row = mat;row < mat + ROW_SIZE;row++){
for(auto col = *row + (row - mat);col < *row + COL_SIZE;++col){
upper_sum += *col;
}
}
for(auto row = mat;row < mat + ROW_SIZE;row++){
for(auto col = *row ;col < *row + (row - mat) + 1;++col){
lower_sum += *col;
}
}
for(auto row = mat;row < mat + ROW_SIZE;row++){
auto col = *row + (row - mat);
diognal_sum += *col;
}
return 0;
}
三、回文串
#include<iostream>
#include<cstring>
using namespace std;
string s;
int len;
bool Pald(int i,int j){
return (s[i] == s[j])?((i == j || i + 1 == j)?true:Pald(i+1,j-1)):false;
}
int main(){
char ch = getchar();
while(ch != '\n'){
if(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')){
if(ch >= 'A') s[len++] = ch - 'A' + 'a';
else s[len++] = ch;
}
ch = getchar();
}
cout << (Pald(0,len - 1)?"Yes":"No");
return 0;
}
四、约瑟夫问题
vector用吐了
#include<iostream>
#include<vector>
using namespace std;
vector<int> alive;
int n,m,ans;
int main(){
cin >> n >> m;
for(int i = 0;i < n;++i){
alive.push_back(1);
}
vector<int>::iterator it = alive.begin();
while (ans < n-1){
int cnt = 1;
while (cnt < m){
if(it == alive.end()) it = alive.begin();
else it++;
while (*it != 1){
if(it == alive.end()) it = alive.begin();
else it++;
}
cnt++;
}
*it = 0;
if(it == alive.end()) it = alive.begin();
else it++;
while (*it != 1){
if(it == alive.end()) it = alive.begin();
else it++;
}
ans++;
}
cout<<it - alive.begin()+1;
return 0;
}
链表实现,一开始用vector遍历实在是要疯了
#include<iostream>
#include<vector>
using namespace std;
vector<int> alive[3];
int n,m,ans;
int main(){
cin >> n >> m;
for(int i = 0;i < n;++i){
alive[0].push_back(1);
alive[1].push_back(i+1);
alive[2].push_back(i-1);
}
alive[1][n-1] = 0;
alive[2][0] = n-1;
int l = 0;
while (ans < n-1){
int cnt = 1;
while (cnt < m){
l = alive[1][l];
cnt++;
}
alive[1][alive[2][l]] = alive[1][l];
alive[2][alive[1][l]] = alive[2][l];
alive[0][l] = 0;
l = alive[1][l];
ans++;
}
for(int i = 0;i < n;++i){
if(alive[0][i]) cout<<i+1;
}
return 0;
}