参考http://hi.baidu.com/zdg102/blog/item/9eafab44f711538ab2b7dcfb.html 上的思路! #include<iostream> using namespace std; const int MAXNUM=1000; int val[MAXNUM+2],width; long runLen[MAXNUM+2],mark[MAXNUM<<2+2],maxxx; struct node { long num; node *next; }*head; void createLink(node **l,long n) { if(*l==NULL) { head=*l=(node*)malloc(sizeof(node)); head->num=n; } else { (*l)->next=(node*)malloc(sizeof(node)); (*l)=(*l)->next; (*l)->num=n; (*l)->next=NULL; } } node* bubbleSort(node **p,int len) { int i,temp; node *q,*first; first=*p; for(i=0;i<len;i++) { *p=first; while((*p)!=NULL) { q=(*p)->next; if(q==NULL)break; else { if((*p)->num > q->num) { temp=(*p)->num; (*p)->num=q->num; q->num=temp; } if((*p)->num == q->num) { (*p)->next=q->next; free(q); } } (*p)=(*p)->next; } } return first; } int absa(int a) { if(a<0) return -a; return a; } int getValueFromNum(long num) { int i=0; while(num>0) num-=runLen[i++]; i--; //cout<<i<<" "<<val[i]; return val[i]; } int getNum(long n) { long num[8]; int i,ans,temp,o; memset(num,0,sizeof(num)); if(n-width>0) { num[0]=n-width; if(num[0]%width != 1) num[1]=num[0]-1; if(num[0]%width != 0) num[2]=num[0]+1; } if(n%width != 1) num[3]=n-1; if(n%width != 0) num[4]=n+1; if(n+width<=maxxx) { num[5]=n+width; if(num[5]%width != 1) num[6]=num[5]-1; if(num[5]%width != 0) num[7]=num[5]+1; } ans=0; o=getValueFromNum(n); for(i=0;i<8;i++) { if(num[i]>0) { temp=absa(o-getValueFromNum(num[i])); ans=temp > ans?temp:ans; } } return ans; } void calculate(node *head) { node *p=head; int value,dis,temp; long n1,n2,len=0; if(p!=NULL) { value=getNum(p->num); len=1; } while(p!=NULL) { n1=p->num; p=p->next; if(p!=NULL) { n2=p->num; dis=n2-n1; if(dis>1) { temp=getNum(n1+1); if(temp==value) { len+=dis-1; } else { printf("%d %d/n",value,len); len=dis-1; value=temp; } } temp=getNum(n2); if(temp==value) { len++; } else { printf("%d %d/n",value,len); len=1; value=temp; } } else { printf("%d %d/n",value,len); } } printf("0 0/n"); } int main() { int i,len; long n; node *p=NULL; head=p; i=0,n=0,len=0; cin>>width; while(width!=0) { maxxx=0; while(cin>>val[i]>>runLen[i]&&(val[i]||runLen[i])) { maxxx+=runLen[i]; i++; } for(int j=0;j<i;j++) { n++; createLink(&p,n); if(n-width>0) createLink(&p,n-width); if(n+width<=maxxx) createLink(&p,n+width); n+=runLen[j]-1; createLink(&p,n); if(n-width>0) createLink(&p,n-width); if(n+width<=maxxx) createLink(&p,n+width); len+=6; } head=bubbleSort(&head,len); printf("%d/n",width); calculate(head); p=NULL; head=p; i=0,n=0,len=0; cin>>width; } printf("0/n"); return 0; }