Time Limit: 2000MS | Memory Limit: 65536K | |
Total 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
Lines 2.. N+1: Each line contains a single integer: line i+1 describes the grumpiness of cow i.
Output
Sample Input
3 2 3 1
Sample Output
7
Hint
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
能想到这个式子还是很厉害的,,,
因为必须要有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;
}