此题是一个与我的上篇文章  “东东的女朋友”  极为类似的算法的一道题,依然是贪心算法的应用,针对于此题,需要注意的是不可以同时移动的

情况(Impossible)的第3种,和可以移动(Possible)的情况的第二种(见下图):

下面代码及解释如下:

View Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int s;
int t;
}count[1000];
int flag[1000];
int cmp(const void *a ,const void *b)
{
struct node *c = (struct node *)a;
struct node *d = (struct node *)b;
return c->s - d->s;
}

int main()
{
int i,j,k,n,m,p,q,sum,e;
scanf("%d",&n);
while(n--)
{
memset(count,0,sizeof(count)); ////这2个置0还是挺重要的
memset(flag,0,sizeof(flag)); ////
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%d%d",&p,&q);
if(p<q) ////要注意
{
count[i].s=p;
count[i].t=q;
}
else
{
count[i].s=q;
count[i].t=p;
}
}
qsort(count,m,sizeof(count[0]),cmp);////
e=count[0].t;
sum=1; ////sum 记的是不同时移动的次数
flag[0]=1;
i=1; //// 下标为i的是循环中判断的
j=1; //// j 为判断过的个数
while(i<m&&j<m)
{
if(flag[i]==0&&count[i].s>e+1) ////能同时移动桌子的情况 1
{
flag[i]=1;
e=count[i].t;
j++;
}
else if(flag[i]==0&&count[i].s==e+1&&e%2==0) ////能同时移动桌子的情况 2
{
flag[i]=1;
e=count[i].t;
j++;
}
if(i==m-1&&j<m)
{
for(k=0;k<m;k++)
{
if(flag[k]==0)
{
i=k;
flag[i]=1;
e=count[i].t;
sum++;
j++;
break;
}
}
}
i++;
}
printf("%d\n",sum*10);
}
return 0;
}



posted on 2011-12-08 10:31  world_ding  阅读(201)  评论(0编辑  收藏  举报