zoj 1025 Wooden Sticks

题目见:zoj 1025

先对木棒按照长度进行排序,然后再计算对应重量构成的数组中非递减子序列的个数。

相关代码(悲催的是该代码不能在poj1065hdoj1051 下通过,懒得看具体是什么原因了)

/* zoj 1025 Wooden sticks */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 5010

struct stick{
  int length;
  int weight;
};
typedef struct stick stick;

int cmpStick(const void * a, const void * b);
int countSubsequence(int a[], int length);
int main(void)
{
  int caseNum,n,i;
  stick sticks[MAX];
  int weights[MAX];

  scanf("%d", &caseNum);
  while(caseNum-- > 0)
    {
      scanf("%d", &n);
      for(i = 0; i < n; i++)
	{
	  scanf("%d %d", &sticks[i].length,&sticks[i].weight);
	}
      qsort(sticks,n,sizeof(stick),cmpStick);
      for(i = 0; i < n; i++)
	weights[i] = sticks[i].weight;
      printf("%d\n", countSubsequence(weights,n));
    }
  return 0;
}
int cmpStick(const void *a, const void *b)
{
  stick x,y;
  x = *(stick  const *)a;
  y = *(stick const *)b;
  if(x.length > y.length)
    return 1;
  else
    return 0;
}
int countSubsequence(int a[], int length)
{
  int isVisited[MAX];
  int i,count,prevIndex;
  int resCount = 0;
  memset(isVisited,0,sizeof(isVisited));
  for(count =0; count < length; )
    {
      for(i = 0; i < length; i++)
	if(!isVisited[i])
	  {
	    prevIndex = i;
	    isVisited[i] = 1;
	    count++;
	    break;
	  }
      if(i == length)
	break;
      for(i = prevIndex+1; i < length; i++)
	if(!isVisited[i])
	  {
	    if(a[prevIndex] <= a[i])
	      {
		isVisited[i] = 1;
		count++;
		prevIndex = i;
	      }
	  }
      resCount++;
    }
  return resCount;
}
 

你可能感兴趣的:(c,ACM,ZOJ)