zoukankan      html  css  js  c++  java
  • 【置换,推理】UVa 1315

    Dsecription 

    n participants of «crazy tea party» sit around the table. Each minute one pair of neighbors can change their places. Find the minimum time (in minutes) required for all participants to sit in reverse order (so that left neighbors would become right, and right - left).

    Input 

    The first line is the amount of tests. Each next line contains one integer n (1 <= n <= 32767) - the amount of crazy tea participants.

    Output 

    For each number n of participants to crazy tea party print on the standard output, on a separate line, the minimum time required for all participants to sit in reverse order.

    Sample Input 

    3
    4
    5
    6
    

    Sample Output 

    2
    4
    6

    题意:有n个人坐成一圈。相邻间可以交换,问至少交换多少次能达到逆序,即左右相邻的数交换。

    分析:从中间分开,很明显1~(n/2)号往左交换,(n/2)~n号往右交换。比如:
    n = 6时:
      1 2 3 | 4 5 6
      1 3 2 | 5 4 6
      3 1 2 | 5 6 4 (以上3,4分别移至两侧)
      3 2 1 | 6 5 4 (2,5移至两侧)
      
      以上完成逆序变换;

    n = 7时:
      1 2 3 4 | 5 6 7
        ...
      4 1 2 3 | 6 7 5
        ...
      4 3 1 2 | 7 6 5
      4 3 2 1 | 7 6 5
    这样每个数需要交换的次数分别为 (偶)0 1,2,...,(n/2)-1, (n/2)-1,...,2,1,0
                    (奇)0 1,2,...,(n/2), (n/2)-1,...,2,1,0
    求和即可。

    【代码】:代码可能略繁琐。自己可以简化一下。
     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 int main()
     5 {
     6     int T; scanf("%d", &T);
     7     while(T--)
     8     {
     9         int n, ans = 0; scanf("%d", &n);
    10         if(n%2)
    11         {
    12             int num = n/2;
    13             ans = (1+(num-1)) * (num-1);
    14             ans += num;
    15         }
    16         else
    17         {
    18             int num = n/2;
    19             ans = (1+(num-1)) * (num-1);
    20         }
    21         cout << ans << endl;
    22     }
    23     return 0;
    24 }


  • 相关阅读:
    yum插件yum-fastestmirror
    mysql利用yum安装指定数据存放路径
    快速搭建Seeddms文档管理系统
    Oracle单实例启动多个实例
    HTTP 304状态分析
    Oracle快速克隆安装
    Linux安装SQLite轻量级数据库
    redhat利用yum快速搭建LAMP环境
    将博客搬至CSDN
    GenericServlet 、Servlet和httpServler他们之间的关系
  • 原文地址:https://www.cnblogs.com/LLGemini/p/4322233.html
Copyright © 2011-2022 走看看