Sicily 1278. Soldiers

来源:互联网 发布:淘宝美工可以自学吗 编辑:程序博客网 时间:2024/04/30 07:26

1278. Soldiers

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

The soldiers of the moon army are standing in a line, some of them looking to the left end of the line, other - to the right end of the line. Therefore, some couples of neighbors in the line could stand face to face, some couples - back to back, and some - back to face (or face to back which is the same). By a command the soldiers start to turn. One turn applies to a single couple of soldiers that are standing face to face. After the turn the soldiers are standing back to back. For a given line of soldiers it is necessary to decide whether it is possible to order the soldiers by consecutive turns in such a way that there is no couple of soldiers in the line standing face to face. If this is possible - find the minimum number of turns. 

Input

The input file contains a sequence of input data sets. In the first line of the input file there is a single number t – amount of tests (0 < t < 10). Next lines contain test data. The first line of each test contains a natural number k (0 < k < 1000), which gives the amount of next  lines for current test. These lines designate the row of soldiers. The length of each line is no more than 50. The soldiers position in the line is given with a sequence of two symbols: ‘<’ – the soldier faces towards left, ‘>’ – the soldier faces towards right. 

Output

The output should be printed on the standard output. For each given input data set, print one number in a single line. If the arrangement for fight is impossible (the number of turns is infinite) for current test, you must print -1. If possible, print the minimal number of turns to reach this arrangement.

Sample Input

32><><1><<<<3<<>

Sample Output

340

Problem Source

ZSUACM Team Member

也是在看了大神的代码之后幡然懂的:

首先,对于两个士兵><,调换完之后是<>,那就相当于交换了彼此;

其次,最后的士兵状态必然是<<<<...<>...>>>>;

为什么呢,因为首先其中不可能有><,其次,假如是<<<<<那么最后一步操作的时候必然会导致两个士兵都调换,也就是上述士兵状态是不可能出现的,因为只有面对面的士兵才可以被调换(><  --->  <>);

这么一来,就相当于对两种括号的排序咯,而且是冒泡排序,怎样有最少的步数呢?

考虑最终状态是<都在左边,那么也就是把<移向左边,那么最靠近左边的<先移动可以确保最少的交换次数:


#include <stdio.h>#include <iostream>#include <string>using namespace std;int main() {        std::ios::sync_with_stdio(false);        int case_num;    cin >> case_num;        while (case_num--) {        int n;        cin >> n;        string s;        while (n--) {            string temp;            cin >> temp;            s += temp;        }        int i, pos, sum = 0;        for (i = 0, pos = 0; i < (int)s.size(); i++) {            if (s[i] == '<') {                sum += i - pos;                pos++;            }        }        cout << sum << endl;    }    return 0;}    


0 0
原创粉丝点击