【POJ3270】【Cow Sorting】

来源:互联网 发布:自学编程怎么找工作 编辑:程序博客网 时间:2024/05/21 11:03

Cow Sorting
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 6411 Accepted: 2488

Description

Farmer John's N (1 ≤ N ≤ 10,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage FJ's milking equipment, FJ would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (not necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes FJ a total of X+Y units of time to exchange two cows whose grumpiness levels are X and Y.

Please help FJ calculate the minimal time required to reorder the cows.

Input

Line 1: A single integer: N
Lines 2..N+1: Each line contains a single integer: line i+1 describes the grumpiness of cow i

Output

Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.

Sample Input

3231

Sample Output

7

Hint

2 3 1 : Initial order. 
2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4). 
1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3).

Source

USACO 2007 February Gold

能想到这个式子还是很厉害的,,,

因为必须要有dp[i][j-1] 和dp[i+1][j] 但是这样又多了,又得减去。还有2个端点没有考虑到。


#include <iostream>#include <cstring>#include <cmath>#include <queue>#include <stack>#include <list>#include <map>#include <set>#include <string>#include <cstdlib>#include <cstdio>#include <algorithm>using namespace std;    int n,m;int a[1010];int dp[1010][1010];int main(){    scanf("%d%d",&n,&m);for(int i=1;i<=n;i++){scanf("%d",&a[i]);}for(int i=n;i>=1;i--)for(int j=i;j<=n;j++){dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];if(a[i] > a[j]) dp[i][j] ++;}int l,r;    while(m--){scanf("%d%d",&l,&r);printf("%d\n",dp[l][r]);}    return 0;}


0 0
原创粉丝点击