There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.
We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1 ≤ i ≤ n - 1), such that ai + 1 > ai.
The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of painting.
The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai means the beauty of the i-th painting.
Print one integer — the maximum possible number of neighbouring pairs, such that ai + 1 > ai, after the optimal rearrangement.
5 20 30 10 50 40
4
4 200 100 100 200
2
In the first sample, the optimal order is: 10, 20, 30, 40, 50.
In the second sample, the optimal order is: 100, 200, 100, 200.
思路:思路很简单,就是找到最优解,并将其存进一个地方,再进行比较,但是难就难在怎么实现,代码实现过程中,要记得把已经用过的标记下,下次就跳过他。
代码如下:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[1005],b[1005];
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
int k=0,ans=0;;
for(int i=0; i<n; i++)
{
if(a[i])
{
b[k++]=a[i];
a[i]=0;
for(int j=i+1; j<n; j++)
{
if(a[j]>b[k-1])
b[k++]=a[j],a[j]=0;
}
}
}
for(int i=1; i<n; i++)
if(b[i]>b[i-1])
ans++;
printf("%d\n",ans);
}
}
或者用vector
代码如下:
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<math.h>
#include<map>
using namespace std;
vector<int> ss;
int s[1005];
int b[1005];
int main()
{
memset(s,0,sizeof(s));
memset(b,0,sizeof(b));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&s[i]);
sort(s+1,s+1+n);
for(int i=1;i<=n;i++)
{
if(b[i])
continue;
ss.push_back(s[i]);
int temp=s[i];
for(int j=i+1;j<=n;j++)
{
if(b[j])
continue;
if(temp>=s[j])
continue;
temp=s[j];
b[j]=1;
ss.push_back(s[j]);
}
}
int ans=0;
for(int i=0;i<ss.size()-1;i++)
{
if(ss[i+1]>ss[i])
ans++;
}
printf("%d\n",ans);
}