B题居然WA了。。。。
思路简述: 分别把奇数和偶数提取出来,检验是否已有序,若都有序则必然能交换获得非降序的目标结果。昨天写的时候也是,把两部分分开看是否有序了,但超时了,这告诉我们要善用函数。
#include <bits/stdc++.h>
#define rep(x, a, b) for(int x = a; x <= b; x++)
#define pre(x, a, b) for(int x = b; x >= a; x--)
#define PII pair<int, int>
#define ll long long
using namespace std;
const int N = 1e5+10;
/*2 4 3 5*/
void solve()
{
int n;
cin>>n;
vector<int> odd, even;
rep(i, 1, n)
{
int x;cin>>x;
if(x % 2) even.push_back(x);
else odd.push_back(x);
}
if(is_sorted(odd.begin(), odd.end()) && is_sorted(even.begin(), even.end())) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
int main()
{
int t;
scanf("%d", &t);
while(t -- )
{
solve();
}
return 0;
}
C:
You are given a permutation p1,p2,…,pnp1,p2,…,pn. Then, an undirected graph is constructed in the following way: add an edge between vertices ii, jj such that i<ji<j if and only if pi>pjpi>pj. Your task is to count the number of connected components in this graph.
Two vertices uu and vv belong to the same connected component if and only if there is at least one path along edges connecting uu and vv.
A permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).
Input
Each test contains multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the length of the permutation.
The second line of each test case contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n) — the elements of the permutation.
It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.
题目类型:单调栈
解题思路:挨个把数字二元组压入栈,二元组初始时两个都为本身,不管情况如何都先压入栈。
每次将一个新的二元组压入栈,就比较一下当前栈顶元素cur的second(最小值)与栈顶元素pre的前一个元素的first(最大值)进行比较,若(cur.second < pre.first)则把这两个元素归为一类,弹出这两帧,并压入新的二元组make_pair{max(cur.first, pre.first), min(cur.second,pre.second)}.
重复弹栈比较操作,直到(cur.second < pre.first)不成立。原因 : 5796 , 9 6 相消,但 7 仍然比6 大,也要消。
#include <bits/stdc++.h>
#define rep(x, a, b) for(int x = a; x <= b; x++)
#define pre(x, a, b) for(int x = b; x >= a; x--)
#define PII pair<int, int>
#define ll long long
using namespace std;
const int N = 1e5+10;
/*2 4 3 5*/
void solve()
{
int n;
cin>>n;
stack< PII > st;
rep(i, 1, n)
{
int x; cin>>x;
st.push({x, x});
bool flag = false;
while(st.size() >= 2 && !flag){
PII temp1 = st.top();
st.pop();
PII temp2 = st.top();
st.push(temp1);
if(temp2.first > temp1.second){
st.pop();st.pop();st.push({max(temp1.first, temp2.first), min(temp1.second, temp2.second)});
}else flag = true;
}
}
cout<<st.size()<<endl;
}
int main()
{
int t;
scanf("%d", &t);
while(t -- )
{
solve();
}
return 0;
}