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 }


  • 相关阅读:
    社交类app开发( 仿陌陌 客户端+服务器端)
    iPhone的xib与iPad的xib相互转换
    SVN的搭建
    使用企业证书给iOS应用重签
    [破解版]Unity3d引擎最新稳定版本4.5.5下载(官方最新稳定版本)
    iphone开发资源汇总
    iOS绘图教程
    iOS静态库相关-封装lib
    iOS内存管理策略和实践
    前台中文乱码
  • 原文地址:https://www.cnblogs.com/LLGemini/p/4322233.html
Copyright © 2011-2022 走看看