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 }


  • 相关阅读:
    mysql的缓冲查询和非缓冲查询
    通过中看不中用的代码分析Ioc容器,依赖注入....
    register_shutdown_function AND fastcgi_finish_request
    laravel5源码讲解整理
    ERROR! MySQL is running but PID file could not be found
    读《高性能javascript》笔记(一)
    看php手册2015-03-19版后备注
    rawurlencode / urlencode
    Zen Cart屏蔽中文语言浏览器
    WooCommerce Shortcode 简码使用方式说明
  • 原文地址:https://www.cnblogs.com/LLGemini/p/4322233.html
Copyright © 2011-2022 走看看