卖菜
实现
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int a[N],b[N];
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
b[0] = (a[1]+a[0])/2;
for(int i=1;i<n-1;i++)
{
b[i] = (a[i-1]+a[i]+a[i+1])/3;
}
b[n-1] = (a[n-1]+a[n-2])/2;
for(int i=0;i<n;i++)
{
printf("%d ",b[i]);
}
}
买菜
实现
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 2010;
int n;
PII p[N], q[N];
int get(PII a, PII b)
{
if (a.y < b.x || b.y < a.x) return 0;
return min(a.y, b.y) - max(a.x, b.x);
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ ) cin >> p[i].x >> p[i].y;
for (int i = 0; i < n; i ++ ) cin >> q[i].x >> q[i].y;
int res = 0;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n; j ++ )
res += get(p[i], q[j]);
cout << res << endl;
return 0;
}
元素选择器
思路
需要读取整行,但不知道后续有几个元素,可以使用getline读取整行,再stringstream ssin(str)
多级的后代选择器在匹配时,可以采用贪心的策略:除最后一级外,前面的部分都可以尽量匹配层级小的元素。可以使用栈。
实现
来自acwing-yxc:https://www.acwing.com/activity/content/code/content/893996/
#include<bits/stdc++.h>
using namespace std;
const int N = 105;
int n,m;
vector<string> strs;
struct node
{
int tab; //前面有几个点
string tag,name; //标签和id
int k; //匹配到了第几项
node(string str)
{
int i=0;
while(str[i]=='.') i++;
tab = i;
while(i<str.size() && str[i]!=' ')
{
tag+=tolower(str[i]);
i++;
}
i++;
while(i<str.size()) name+=str[i++];
k = 0;
}
bool check(string& word)
{
if(word[0]=='#')return word == name;
return word ==tag;
}
};
void work(vector<string>& ws)
{
vector<int> res; //存储行号
stack<node> stk;
for(int i=0;i<strs.size();i++)
{
node t(strs[i]);
// cout<<"i:"<<i<<endl;
// cout<<"tag:"<<t.tag<<endl;
// cout<<"name:"<<t.name<<endl;
while(stk.size() && stk.top().tab>=t.tab) stk.pop();
if(stk.size()) t.k = stk.top().k;
if(t.k==ws.size()) t.k--;
if(t.check(ws[t.k]))
{
t.k++;
if(t.k==ws.size()) res.push_back(i+1);
}
stk.push(t);
}
cout<<res.size();
for(auto x:res) cout<<" "<<x;
cout<<endl;
}
int main()
{
cin>>n>>m;
getchar();
string str;
while(n--)
{
getline(cin,str);
strs.push_back(str);
}
while(m--)
{
getline(cin,str);
stringstream ssin(str);
vector<string> ws;
while(ssin>>str)
{
if(str[0]!='#')
{
for(auto& c:str)
c = tolower(c);
}
ws.push_back(str);
}
work(ws);
}
return 0;
}