通过代码,
#include <bits/stdc++.h>
const int N = 1010;
int f[N][N];
//状态表示f[i][j]:str1中前i个元素(str1[0],...,str1[i-1]),str2中前j个元素(str2[0],...,str2[j-1]),组合的公共子序列集合。属性是长度最大。
//状态转移:
//如果str1[i-1] == str2[j-1],f[i][j] = f[i-1][j-1] + 1;
//否则,f[i][j] = max(f[i][j-1], f[i-1][j]);
//最上边初始化为0,最右边初始化为0
using namespace std;
int getMaxCommon(string str1, string str2)
{
int n = str1.size();
for(int i = 0; i <= n; i++) f[i][0] = 0;
for(int j = 0; j <= n; j++) f[0][j] = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(str1[i-1] == str2[j-1]) f[i][j] = f[i-1][j-1] + 1;
else f[i][j] = max(f[i-1][j], f[i][j-1]);
return f[n][n];
}
int main()
{
string str1;
while(cin >> str1)
{
string str2 = str1;
reverse(str1.begin(), str1.end());
int m = getMaxCommon(str1, str2);//求最长公共子序列,可以不连续
//cout << "str1 = " << str1 << ", str2 = " << str2 << endl;
cout << str1.size() - m << endl;
}
return 0;
}
代码,
#include <bits/stdc++.h>
using namespace std;
bool check(char c)
{
if(c >= 'A' && c <= 'Z') return true;
else return false;
}
int main()
{
string s;
while(cin >> s)
{
//从后面开始移动
for(int i = s.size()-1; i >= 0; i--)
{
if(check(s[i]))//如果s[i]是大写字母
{
int j = i;
while(check(s[j]) == true && check(s[j+1]) == false && j+1 < s.size())
{
swap(s[j], s[j+1]);
j++;
}
}
}
cout << s << endl;
}
return 0;
}
代码,
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(cin >> n)
{
vector<int> nums(n);
for(int i = 0; i < n; i++) cin >> nums[i];
map<int,int> cnt;//统计nums数组中数字出现的次数
for(int i = 0; i < n; i++) cnt[nums[i]]++;
int res1 = 0;//差最小的对数
int res2 = 0;//差最大的对数
//求差最小的对数
int flag = false;//判断最小的差是否为0;
for(auto [val1, cnt1] : cnt)
if(cnt1 > 1) {flag = true; break;}
if(flag == true)//最小的差就为0
{
for(auto [val1, cnt1] : cnt)
if(cnt1 > 1) res1 += cnt1 * (cnt1 - 1) / 2;
}
else//此时不存在相同的元素,最小的差就为
{
vector<int> newNum;
for(auto it = cnt.begin(); it != cnt.end(); it++) newNum.push_back(it->first);
map<int,int> newCnt;
for(int i = 0; i < newNum.size()-1; i++)
newCnt[newNum[i+1]-newNum[i]]++;
res1 = newCnt.begin()->second;
}
//求差最大的对数
res2 = cnt.begin()->second;
auto it = cnt.end();
it--;
res2 *= it->second;
cout << res1 << ' ' << res2 << endl;
}
return 0;
}