这题貌似方法多,效率也不同,先发个水法暴力的(930ms惊险水过):
#include <stdio.h> #include <string.h> #include <stdlib.h> int ncase,n,res,tl,tr; char appear[10000]; struct node { int l,r,color; struct node *next; }; void freelist(struct node * head) { if(head->next==NULL) { free(head); return; } else freelist(head); } int main() { struct node *head,*idx,*pidx,*tmpidx; scanf("%d",&ncase); while (ncase--) { res=0; memset(appear,0,sizeof(appear)); head=(struct node *)malloc(sizeof(struct node)); head->next=NULL; scanf("%d",&n); for (int i=0; i<n; i++) { scanf("%d%d",&tl,&tr); tl-=1; pidx=head; idx=head->next; while (idx!=NULL) { if(idx->l<tl && idx->r<=tr && tl<idx->r) { idx->r=tl; } else if(tl<=idx->l && tr<idx->r && idx->l<tr) { idx->l=tr; } else if(tl<=idx->l && tr>=idx->r) { //delete //printf("delete!\n"); pidx->next=idx->next; free(idx); idx=pidx->next; continue; } else if(idx->l<tl && idx->r>tr) { //add tmpidx=(struct node *)malloc(sizeof(struct node)); tmpidx->l=tr; tmpidx->r=idx->r; tmpidx->color=idx->color; tmpidx->next=idx->next; idx->next=tmpidx; idx->r=tl; } if(idx->l>idx->r) { //delete //printf("delete!\n"); pidx->next=idx->next; free(idx); idx=pidx->next; continue; } pidx=idx; idx=idx->next; } idx=(struct node *)malloc(sizeof(struct node)); idx->l=tl; idx->r=tr; idx->color=i; idx->next=NULL; pidx->next=idx; } idx=head->next; while(idx!=NULL) { //printf("%d %d %d\n",idx->l,idx->r,idx->color); appear[idx->color]=1; idx=idx->next; } for (int i=0; i<n; i++) { if(appear[i]) res++; } printf("%d\n",res); //freelist(head); } }
这个方法实在是太暴力了。。。以至于清空链表会导致超时(囧啊),于是注释掉了
其他方案待更新