C. Sorting by Subsequences
time limit per test
1 second
memory limit per test
256 megabytes
You are given a sequence a1, a2, ..., an 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 ≤ 105) — the length of the sequence.
The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — 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 ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ 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.
Solution
题意:
给出长度为N的一个序列,我们的任务是将其分割成尽可能多的子序列,使得每个子序列自身排序之后,最终的序列是一个递增的序列。
保证每个数只会出现一次。
View Code1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 100000; 4 struct node{int id,value;}a[maxn + 99]; 5 inline bool cmp(node a,node b){return a.value < b.value;} 6 int to[maxn + 99],n, cnt = 0,vis[maxn + 99]; 7 vector<int> q[maxn + 99]; 8 inline void dfs(int x,int idx){ 9 vis[x] = 1; q[idx].push_back(x); 10 if (!vis[to[x]]) dfs(to[x],idx); 11 } 12 int main(){ 13 scanf("%d",&n); 14 for (int i = 1 ; i <= n ; ++i) scanf("%d",&a[i].value),a[i].id = i; 15 sort(a + 1 , a + 1 + n, cmp); 16 for (int i = 1 ; i <= n ; ++i) to[a[i].id] = i; 17 memset(vis,0,sizeof(vis)); 18 for (int i = 1 ; i <= n ; ++i) if (vis[i] == 0) dfs(i,++cnt); 19 cout<<cnt<<endl; 20 for (int i = 1 ; i <= cnt ; ++i){ 21 cout<<q[i].size()<<" "; 22 for (int j = 0 ; j < q[i].size() ; ++j) printf("%d ",q[i][j]); 23 cout<<endl; 24 } 25 return 0; 26 }题解:这是一道有趣的题,似乎只排一排序找一找环就过了....