Probably because this time did not divide Div.1 and Div.2, so the difficulty of feeling the problem is bigger.
Test instructions
Given an arrangement of 1~n and an adjacency matrix A,aij = 1 means that I and j, which can be exchanged, ask that after several exchanges, the order of the most Dictionary order will be obtained.
Analysis:
If A and B are exchangeable, B and C can be exchanged, then A and C can also exchange positions. If the n position is treated as a vertex, and the two exchangeable positions have an edge, the vertices of the same connected component in the graph are interchangeable elements. So it is convenient to use and check the set.
To get the smallest order in the dictionary order, just greedy. Start with the first number, first try 1 can not swap to the first position, otherwise try 2, until you can exchange or there is no smaller number than the beginning of the position. Then continue to try the second number. There is a used tag array in the code that marks whether the number was used before.
1#include <cstdio>2#include <algorithm>3 4 Const intMAXN = -+5;5 CharG[MAXN][MAXN];6 intP[MAXN], A[MAXN], POS[MAXN];//POS records the location of each number7 BOOLUSED[MAXN];//Mark whether each number has been used8 9 intGetParent (intx)Ten { One return(P[x] = = x X:p[x] =GetParent (p[x])); A } - - voidUnion (intXinty) the { - intpx = GetParent (x), py =GetParent (y); - if(px! =py) -P[PX] =py; + } - + intMain () A { at //freopen ("In.txt", "R", stdin); - intN; -scanf"%d", &n); - for(inti =1; I <= N; ++i) P[i] =i; - for(inti =1; I <= N; ++i) scanf ("%d", &a[i]); - for(inti =1; I <= N; ++i) scanf ("%s", G[i] +1); in - for(inti =1; I <= N; ++i) Pos[a[i] =i; to + for(inti =1; I <= N; ++i) - for(intj =1; J <= N; ++j) the if(G[i][j] = ='1') Union (i, j); * $ for(inti =1; I < n; ++i)Panax Notoginseng { -Used[a[i]] =true; the for(intj =1; J < A[i]; ++j) + { A if(Used[j])Continue; the if(GetParent (i) = =GetParent (Pos[j])) + { -Used[a[i]] =false; $USED[J] =true; $ intQ =Pos[j]; -Std::swap (A[i], a[q]);//Exchange two elements -Std::swap (Pos[a[i]], pos[a[q]]);//swap the positions of each number at the same time the Break; - }Wuyi } the } - Wu for(inti =1; I < n; ++i) printf ("%d", A[i]); -printf"%d\n", A[n]); About $ return 0; -}
code June
Codeforces Good Bye B. New year permutation