Title Description
Sorting is a very frequent computational task. Now consider sorting problems with up to three values. A practical example is when we give a winner of a competition a sort of gold and silver medal. The possible values in this task are only three and 3. We put him in ascending order by means of an exchange.
Write a program that calculates the minimum number of exchanges required for a given sequence of one-and-a-line numbers, in ascending order
input/output format
Input format:
First line:
Number of medals N (1 <= n <= 1000)
Line 2nd to section n+1:
Each line is a number that represents the medal. Total n rows. (1.. 3)
Output format:
A total of one row, a number. Represents the minimum number of exchanges required to rank in ascending order.
input/Output sampleInput Sample # #:
9221333231
Sample # # of output:
4
Description
Usaco 2.1
Translation from Nocow
First count each number of how many, then find the number of dislocation, with a minimum number of steps to exchange it over.
Take a sample example:
2 2 1 3 3 3 2 3 1
1 of them were 2, 2 had 3, 3 had 4. The correct sequence should be:
1 1 2 2 2 3 3 3 3
Visible, originally is 1 of the position, there are 2 2, recorded as e[1][2]=2;
Originally 2 of the position, there are 1 1 and 2 3 are recorded as e[2][1]=1;e[2][3]=2;
Originally 3, there were 1 1 and a 2. Recorded as e[3][1]=1;e[3][2]=2;
Next, if e[i][j]>0&&e[j][i]>0
Sum+=min (E[i][j],e[j][i]);
But in the example, E[1][2]>e[2][1], that is, there is still dislocation exists, how to do?
Take a look at the following set of examples:
2 3 1
Three numbers are not in their place, but they can be ordered in just two steps:
2 1 3
1 2 3
The rest of the numbers must be such a situation, so statistics on the dislocation number, also must be a multiple of three, for every three dislocation, we only need two times can be solved.
#include <cstdio>
int a[4],e[4][4],i,n,s,sum,j,x[1001];
int main ()
{
scanf ("%d", &n);
For (i=1;i<=n;i++)
{
scanf ("%d", &x[i]);
a[x[i]]++;
}
For (i=1;i<=a[1];i++)
{
if (x[i]!=1)
{
e[1][x[i]]++;
s++;
}
}
For (i=a[1]+1;i<=a[1]+a[2];i++)
{
if (x[i]!=2)
{
e[2][x[i]]++;
s++;
}
}
For (i=a[1]+a[2]+1;i<=a[1]+a[2]+a[3];i++)
{
if (x[i]!=3)
{
e[3][x[i]]++;
s++;
}
}
if (e[1][2]<e[2][1]) sum+=e[1][2];
else sum+=e[2][1];
if (e[1][3]<e[3][1]) sum+=e[1][3];
else sum+=e[3][1];
if (e[3][2]<e[2][3]) sum+=e[3][2];
else sum+=e[2][3];
sum+= ((s-2*sum)/3) * *;
printf ("%d", sum);
return 0;
}
(Luogu series) Luogu p1459 sorting of three values