题解:CodeForces 843A Sorting by Subsequences[模拟/排序]
CodeForces 843A
A. Sorting by Subsequences
time limit per test: 1 second
memory limit per test: 256 megabytes
inputstandard input
outputstandard output
You are given a sequence \(a_1, a_2, ..., a_n\) consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.
Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.
Every element of the sequence must appear in exactly one subsequence.
Input
The first line of input data contains integer \(n (1 ≤ n ≤ 10^5)\) — the length of the sequence.
The second line of input data contains n different integers \(a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9)\) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.
Output
In the first line print the maximum number of subsequences \(k\) , which the original sequence can be split into while fulfilling the requirements.
In the next \(k\) lines print the description of subsequences in the following format: the number of elements in subsequence \(c_i (0 < c_i ≤ n)\), then \(c_i\) integers \(l_1, l_2, ..., l_{c_i} (1 ≤ l_j ≤ n)\) — indices of these elements in the original sequence.
Indices could be printed in any order. Every index from \(1\) to \(n\) must appear in output exactly once.
If there are several possible answers, print any of them.
Examples
input 1
6
3 2 1 6 5 4
output 1
4
2 1 3
1 2
2 4 6
1 5
input 2
6
83 -75 -49 11 37 62
output 2
1
6 1 2 3 4 5 6
我的题解
想象一下,如果要把一个数替换成应该放在这个位置上的数的话,
那么替换之后另一个位置上的数不一定会对应,那么再进行替换
以此类推,会拉出一长串的数
这就是对这串数排序的最短的序列
在遍历的时候加一个计数
然后其他的就按顺序输出就好了
我的代码
#include <bits/stdc++.h>
#define int long long
int t,ans;
const int N = 1e5+10;
int a[N];
int b[N];
std::map<int,std::pair<int,std::vector<int> > > mp;
std::map<int,int> index;
void solve()
{
int n;
std::cin >> n;
for(int i = 1 ; i <= n ; i ++)
{
std::cin >> a[i];
b[i] = a[i];
index[a[i]] = i;
}
std::sort(b+1,b+n+1);
int i;
for(i = 1 ; i <= n; i ++)
{
if(mp[i].first < 0) continue;
else
{
std::vector<int> out;
out.push_back(i);
int t = i;
mp[i].first++;
while(b[t] != a[i])
{
t = index[b[t]];
out.push_back(t);
mp[t].first = -1;
}
std::sort(out.begin(),out.end());
mp[i].second = out;
ans ++;
}
}
std::cout << ans << "\n";
for(int i = 1 ; i <= n ; i ++)
{
if(mp[i].first!=-1)
{
std::cout << mp[i].second.size() << " ";
for(int j = 0 ; j < mp[i].second.size() ; j ++)
std::cout << mp[i].second[j] << " ";
std::cout << "\n";
}
}
}
signed main()
{
solve();
return 0;
}
有什么出现纰漏的地方还请大家在评论区指出!谢谢!
posted on 2024-07-14 14:24 Jiejiejiang 阅读(1) 评论(0) 编辑 收藏 举报