【逆序对】In the Army Now

 Ural 1090

1090. In the Army Now

Time Limit: 1.0 second
Memory Limit: 16 MB
The sergeant ordered that all the recruits stand in rows. The recruits have formed K rows with N people in each, but failed to stand according to their height. The right way to stand in a row is as following: the first soldier must be the highest, the second must be the second highest and so on; the last soldier in a row must be the shortest. In order to teach the young people how to form rows, the sergeant ordered that each of the recruits jump as many times as there are recruits before him in his row who are shorter than he. Note that there are no two recruits of the same height.
The sergeant wants to find which of the rows will jump the greatest total number of times in order to send this row to work in the kitchen. Help the sergeant to find this row.

Input

The first line of the input contains two positive integers N and K (2 ≤  N ≤ 10000, 1 ≤  K ≤ 20). The following K lines contain N integers each. The recruits in each row are numbered according to their height (1 — the highest, N — the shortest). Each line shows the order in which the recruits stand in the corresponding row. The first integer in a line is the number of the first recruit in a row and so on. Therefore a recruit jumps as many times as there are numbers which are greater than his number in the line before this number.

Output

You should output the number of the row in which the total amount of jumps is the greatest. If there are several rows with the maximal total amount of jumps you should output the minimal of their numbers.

Sample

inputoutput
3 3
1 2 3
2 1 3
3 2 1
3

 

容易看出是找逆序对,直接用归并排序就行了

 

#include <cstdio>

long n;long k;
long height[10010];
long tmp[10010];
long _ans = 0;
void merge(long l,long mid,long r)
{
	long ltop = l-1;
	long rtop = mid;
	for (long i=1;i<r-l+2;i++)
	{
		if (rtop>=r || (ltop<mid && height[ltop+1]<=height[rtop+1]))
			tmp[i] = height[++ltop];
		else
		{
			_ans += mid-ltop;
			tmp[i] = height[++rtop];
		}
	}
	for (long i=l;i<r+1;i++)
	{
		height[i] = tmp[i-l+1];
	}	
}

void merge_sort(long l,long r)
{
	if (l == r) return;
	long mid = (l+r)>>1;
	merge_sort(l,mid);
	merge_sort(mid+1,r);
	merge(l,mid,r);
}

int main()
{
	scanf("%ld%ld",&n,&k);
	long max = -0x7f7f7f7f;
	long ans = 0;
	for (long i=1;i<k+1;i++)
	{
		_ans = 0;
		for (long j=1;j<n+1;j++)
		{
			scanf("%ld",height+j);
		}
		merge_sort(1,n);
		if (_ans > max)
		{
			max = _ans;
			ans = i;
		}
		#ifdef Debug
//		printf("---");
//		for (long j=1;j<n+1;j++)
//		{
//			printf("%ld ",height[j]);
//		}
//		printf("---\n");
		#endif
	}
	printf("%ld",ans);
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值