hdu2272: Minimize The Difference

hdu2272: http://acm.hdu.edu.cn/showproblem.php?pid=2272
题意:给出n个人的预期排名,问怎样的排名使得所有人的实际排名与预期排名之差的绝对值的和最小 贪心法:将预期排名从小到大排序,再从1~n名依次给他们排名,则所求值最小。
code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
struct str
{
    char s[30];
    int m;
}v[200];
bool cmp(str a,str b)
{
    return a.m<b.m;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++)
            scanf("%s%d",v[i].s,&v[i].m);
        sort(v,v+n,cmp);
        int ans=0;
        for(int i=0;i<n;i++)
        {
            ans=ans+abs(i+1-v[i].m);
        }
        printf("%d\n",ans);
    }
}
/*input:
7
a 1
b 2
c 2
d 1
e 5
g 7
f 7
output:
5
*/

posted on 2012-07-25 21:41  acmer-jun  阅读(172)  评论(0编辑  收藏  举报

导航