Codeforces 653C - Bear and Up-Down 暴力

C. Bear and Up-Down
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

The life goes up and down, just like nice sequences. Sequence t1, t2, …, tn is called nice if the following two conditions are satisfied:

ti < ti + 1 for each odd i < n;
ti > ti + 1 for each even i < n. 

For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.

Bear Limak has a sequence of positive integers t1, t2, …, tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
Input

The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence.

The second line contains n integers t1, t2, …, tn (1 ≤ ti ≤ 150 000) — the initial sequence. It’s guaranteed that the given sequence is not nice.
Output

Print the number of ways to swap two elements exactly once in order to get a nice sequence.
Examples
Input

5
2 8 4 7 7

Output

2

Input

4
200 150 100 50

Output

1

Input

10
3 2 1 4 1 4 1 4 1 4

Output

8

Input

9
1 2 3 4 5 6 7 8 9

Output

0

Note

In the first sample, there are two ways to get a nice sequence with one swap:

Swap t2 = 8 with t4 = 7.
Swap t1 = 2 with t5 = 7. 

In the second sample, there is only one way — Limak should swap t1 = 200 with t4 = 50.

题意:
nice的意思是满足:
ti < ti + 1 for each odd i < n;
ti > ti + 1 for each even i < n.
给的序列一定不是nice,问交换一次可以使得序列nice的方法数。

分析:
找出所有不满足条件的点,显然交换的目的是使得不满足条件的点让他满足条件,那么交换的点一定有一个是不满足条件的点和它的邻接点,取第一个不满足条件的点,更其他的点交换,然后判断一下是否可以使得所有的点满足条件==也就是只判断一下原先不满足条件的点和交换的点是否满足条件即可。
如果不满足条件的点多于4个,那么交换一次肯定是不可以的。因为交换一次最多影响4个点。

#include<bits/stdc++.h>
using namespace std;
const int N=1500009;
int t[N],n;
bool ok(int i)
{
    if(i<1||i>=n)return 1;
    if((i&1)&&t[i]>=t[i+1])return 0;
    if(!(i&1)&&t[i]<=t[i+1])return 0;
    return 1;
}
vector<int>bd;
bool check(int a,int b)
{
    bool flag=1;
    swap(t[a],t[b]);
    for(int i=0;i<bd.size();i++)if(!ok(bd[i]))flag=0;
    if(!ok(a)||!ok(a-1)||!ok(b)||!ok(b-1))flag=0;
    swap(t[a],t[b]);
    return flag;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&t[i]);
    for(int i=1;i<n;i++)if(!ok(i))bd.push_back(i);

    if(bd.size()>4){
        printf("0\n");return 0;
    }
    int x=bd[0];
    int ans=0;
    for(int i=1;i<=n;i++)if(check(i,x))ans++;
    for(int i=1;i<=n;i++)if(check(i,x+1))ans++;
    if(check(x,x+1))ans--;
    printf("%d\n",ans);
    return 0;
}
posted @ 2016-05-08 13:03  HARD_UNDERSTAND  阅读(336)  评论(0编辑  收藏  举报