843A - Sorting by Subsequences
843A - Sorting by Subsequences
还好之前了解过一点白书上的permutation!
我写的递归,其实很容易直接写成递推啊
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5+10; 4 int res; 5 int nex[maxn]; 6 struct Node{ 7 int id,x; 8 bool operator<(const Node &a)const { 9 return x<a.x; 10 } 11 }p[maxn]; 12 int vis[maxn]; 13 vector<int> v[maxn]; 14 void dfs(int u){ 15 vis[u]=1; 16 v[res].push_back(u); 17 if(!vis[nex[u]]) dfs(nex[u]); 18 } 19 int main(){ 20 int n; 21 while(scanf("%d",&n)!=EOF){ 22 res=0; 23 for(int i=0;i<=n;i++) v[i].clear(); 24 for(int i=1;i<=n;i++){ 25 scanf("%d",&p[i].x); 26 p[i].id=i; 27 } 28 sort(p+1,p+n+1); 29 for(int i=1;i<=n;i++){ 30 nex[i]=p[i].id; 31 } 32 memset(vis,0,sizeof(vis)); 33 for(int i=1;i<=n;i++) if(!vis[i]){ 34 dfs(i); 35 res++; 36 } 37 printf("%d\n",res); 38 for(int i=0;i<res;i++){ 39 printf("%d",v[i].size()); 40 for(int j=0;j<v[i].size();j++) printf(" %d",v[i][j]); 41 puts(""); 42 } 43 } 44 }
tourist~~
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 const int N = 1234567; 6 7 pair <int, int> a[N]; 8 int p[N]; 9 bool was[N]; 10 11 int main() { 12 int n; 13 scanf("%d", &n); 14 for (int i = 0; i < n; i++) { 15 scanf("%d", &a[i].first); 16 a[i].second = i; 17 } 18 sort(a, a + n); 19 for (int i = 0; i < n; i++) { 20 p[i] = a[i].second; 21 } 22 vector < vector <int> > res; 23 for (int i = 0; i < n; i++) { 24 if (was[i]) { 25 continue; 26 } 27 int x = i; 28 vector <int> cycle; 29 while (!was[x]) { 30 was[x] = true; 31 cycle.push_back(x); 32 x = p[x]; 33 } 34 res.push_back(cycle); 35 } 36 int cnt = res.size(); 37 printf("%d\n", cnt); 38 for (int i = 0; i < cnt; i++) { 39 int cc = res[i].size(); 40 printf("%d", cc); 41 for (int j = 0; j < cc; j++) { 42 printf(" %d", res[i][j] + 1); 43 } 44 printf("\n"); 45 } 46 return 0; 47 }