uva 1620 Lazy Susan 树状数组

题目传送门:点击打开链接

题意是给你按一定顺序的n个数,你可以颠倒任意连续4个数的顺序,使这n的数变为1,2,3,4..n;

这题先要知道 什么是逆序数?

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序数的总数就是这个排列的逆序数。

例如:

n=8

1 2 3 4 5 6 8 7   他的逆序数为 0+0+0+0+0+0+1+0=1 ,为奇排列

7 1 2 3 4 5 6 8   他的逆序数为 6+0+0+0+0+0+0+0=6, 偶排列

接下来 我们先假设这个4个数序列 逆序数为 x,当我们颠倒4个连续的数的顺序,这个序列的逆序数变为 6-x,所以我们可以得出逆序数的变化值为 6-2*x,2*x一定为偶数,即6-2*x也一定为偶数。

而我们知道1,2,3,4.....n的逆序数为 0  即偶数,所以我们颠倒任意4个连续的数时,这个序列的逆序数变化为偶数,偶数-偶数=偶数,偶数+偶数=偶数,奇数-偶数=奇数,奇数+偶数=奇数。

所以我们只要求出所给的序列的逆序数为偶数时就可以 变为1,2......n的序列

这里我发现:1.n为偶数时,总会有序列的逆序数为偶数 2.当n为奇数时,并且这个所给的序列的逆序数为奇数,不管怎么变换 他的逆序数不能变为 偶数。

(注:我这里说的变换为 1,2,3,4,5 变为 2,3,4,5,1或5,1,2,3,4)

我在这里求的逆序列 用的树状数组求的逆序数(n*logn),当然暴力也可以。。

#include 
#include 
#include 
using namespace std;
int n;
int data[1100];
int brr[510];
int query(int x)
{
    int res=0;
    while(x)
    {
        res+=brr[x];
        x-=x&(-x);
    }
    return res;
}
void xiu(int x)
{
    while(x<=n)
    {
        ++brr[x];
        x+=x&(-x);
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(int i=0;i>data[i];
            data[i+n]=data[i];
        }
        bool is=false;
        for(int i=0;i
Lazy Susan
Time Limit: 3000MS     64bit IO Format: %lld & %llu

Submit Status uDebug

Description

Download as PDF

There are N marbles, which are labeled 1, 2,..., N . The N marbles are put in a circular track in an arbitrary order. In the top part of the track there is a ``lazy Susan", which is a tray that can hold exactly 4 marbles. The tray can be rotated, reversing the orientation of the four marbles. The tray can also be moved around the track in both directions. 

For example, 9 marbles 1, 9, 8, 3, 7, 6, 5, 4, 2 are put in the circular track in clockwise order as shown in the following figure. This figure also shows how the tray is moved and rotated. 

Trung wants you to arrange the marbles by moving and rotating the tray so that when listing the marbles from some position in the track in clockwise order, we get (1, 2,..., N) . Your task is to write a program to tell Trung that either this can be done or not. 

Input 

The input file consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 100. The following lines describe the data sets. 

For each data set, the first line contains the integer N (8N500) . The second line describes the initial state of the track. It contains N numbers which are the labels of the marbles when listing in clockwise order. 

Output 

For each test case, write in one line ``possible" if there exists a solution to arrange the marbles. If not so, write ``impossible". 

Sample Input 

2 
9 
1 9 8 3 7 6 5 4 2 
11  
1 3 2 4 5 6 7 8 9 10 11

Sample Output 

possible 
impossible

你可能感兴趣的:(uva,第八章,高效算法)