1、括号问题
输入一个只包含左右圆括号()的字符串,满足左括号数量和右括号数量一样多。
合法表达式 T 可以是以下四种:
- ()
- (T)
- ()T
- T()
每一次操作,可以把字符串中任意一个括号挪到字符串开头或者结尾,问最少需要多少次操作能把输入变成合法表达式。
#include <iostream>
#include <string>
#include <stack>
#include <vector>
//#include <cstring>
using namespace std;
void fun(string &str,int len){
stack<char> stac;
//char str[st.size()+1];
//strcpy(str,st.c_str());
for(int i=0;i<len;i++){
if(stac.empty())
stac.push(str[i]);
else{
if(stac.top()=='(' && str[i]==')'){
stac.pop();
}
else{
stac.push(str[i]);
}
}
}
cout << stac.size()/2 <<endl;
}
int main() {
int T; // 测试数据的组数
cin>>T;
vector<int> inputs(T);// 每组括号序列的长度 组成的 数组
vector<string> str(T);// 每组括号序列 组成的 数组
for(int i=0;i<T;i++){
cin>>inputs[i];
cin>>str[i];
}
for(int i=0;i<T;i++){
fun(str[i],inputs[i]);
}
return 0;
}
2、矩阵
输入一个整数 n
输出一个 n × n 的矩阵
它是从1到n,先走对角线,然后右上,然后左下,然后右上,然后左下……
比如 n 为 6,输出:
1 7 13 19 25 31
32 2 8 14 20 26
27 33 3 9 15 21
22 28 34 4 10 16
17 23 29 35 5 11
12 18 24 30 36 6
#include <iostream>
#include <vector>
using namespace std;
void fun(int n){
vector<vector<int>> juzhen(n,vector<int>(n));
int k = 1;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
juzhen[j][(i+j)%n]=k++; // 关键点!!!
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout << juzhen[i][j] << " ";
}
cout<<endl;
}
}
int main() {
int T; // 测试数据的组数
cin>>T;
vector<int> inputs(T);// 每组矩阵边长 组成的 数组
for(int i=0;i<T;i++){
cin>>inputs[i];
}
for(int i=0;i<T;i++){
fun(inputs[i]);
}
return 0;
}
3、变量T的初始值是S每次循环,T = T * C + S,循环D次,判断最后的结果和 L 的大小关系。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
long long Day; // 第D天的票数
bool change(vector<long long> &inputs){
for(int i=1;i<=inputs[i];i++){
Day = inputs[2] * inputs[3] + inputs[2];
if(Day>=inputs[0])
return true;
inputs[2]=Day;
}
return false;
}
int main() {
int T; // 测试数据的组数
cin>>T;
vector<vector<long long>> inputs(T,vector<long long>(4));
vector<string> res;
for(int i=0;i<T;i++){
for(int j=0;j<4;j++){
cin>>inputs[i][j];
}
if(change(inputs[i])){
res.push_back("YES");
}
else{
res.push_back("NO");
}
}
for(auto x:res){
cout << x << endl;
}
return 0;
}