解题步骤
这道题的解法同poj1065 http://blog.csdn.net/tiana_/article/details/64636563
,均采用贪心的思想,但对输入进行处理,将桌子从s移到t,s和t的大小关系不确定,用结构体存储这些信息时,确保s小于t。
代码
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Table)
struct Table{
int from;
int to;
struct Table *next;
};
void TableSort(struct Table *head);
int main()
{
int t,n,i,maxn,sum;
struct Table *head,*ptr,*tmp;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
head = (struct Table*)malloc(LEN);
ptr = (struct Table*)malloc(LEN);
scanf("%d%d",&ptr->from,&ptr->to);
if(ptr->from>ptr->to){
maxn = ptr->from;
ptr->from = ptr->to;
ptr->to = maxn;
}
ptr->next = NULL;
head->next = ptr;
for(i=1;i<n;i++){
tmp = (struct Table*)malloc(LEN);
scanf("%d%d",&tmp->from,&tmp->to);
if(tmp->from>tmp->to){
maxn = tmp->from;
tmp->from = tmp->to;
tmp->to = maxn;
}
tmp->next = NULL;
ptr->next = tmp;
ptr = ptr->next;
}
TableSort(head);
ptr = head->next;
sum = 0;
while(ptr!=NULL){
tmp=ptr;
maxn = ptr->to;
while(tmp!=NULL){
if(tmp->next!=NULL&&tmp->next->from>maxn&&maxn%2==0){
maxn = tmp->next->to;
tmp->next = tmp->next->next;
}else if(tmp->next!=NULL&&maxn%2==1&&tmp->next->from>maxn+1){
maxn = tmp->next->to;
tmp->next = tmp->next->next;
}else if(tmp!=NULL){
tmp = tmp->next;
}
if(tmp==NULL)
break;
}
sum++;
ptr = ptr->next;
}
printf("%d\n",sum*10);
}
return 0;
}
//选择 升序
void TableSort(struct Table *head){
struct Table *sm,*p,*q;
int from,to;
p = head->next;
for(;p!=NULL;p=p->next){
sm = p;
from = p->from;
to = p->to;
for(q=p->next;q!=NULL;q=q->next){
if(sm->from>q->from)
sm = q;
else if(sm->from==q->from&&sm->to>q->to)
sm = q;
}
if(sm!=p){
p->from = sm->from;
p->to = sm->to;
sm->from = from;
sm->to = to;
}
}
}