AtCoder Tasks B インタラクティブ練習 (Interactive Sorting)

来源:互联网 发布:js改变color 编辑:程序博客网 时间:2024/06/04 04:57

Problem Statement

This is an interactive task.

There are N balls labeled with the first N uppercase letters. The balls have pairwise distinct weights.

You are allowed to ask at most Q queries. In each query, you can compare the weights of two balls (see Input/Output section for details).

Sort the balls in the ascending order of their weights.

Constraints

  • (N,Q)=(26,1000)(26,100), or (5,7).

Partial Score

There are three testsets. Each testset is worth 100 points.

  • In testset 1, N=26 and Q=1000.
  • In testset 2, N=26 and Q=100.
  • In testset 3, N=5 and Q=7.

这题是AtCoder基础练习题的B题,难度中等,只不过代码量可能比较大。
题意很明确,就是给一个含N个字母的字母列,他们的权重不同,你的任务就是向操作者提出至多Q个问题,从而完成他们的排序。
N与Q的关系有26:1000(解决这个100分) 26 100(100分) 5 7(100分)

第一个100分直接选排就拿下了。
第二个100分用二分(可以说是插入排序法)拿下,不过要优化一下,每次得出大小关系都存起来,避免多次提问。
第三个100分代码量最大,思路倒是清晰,也是种插入排序的优化版,思路与“5个不同的球,如何称7次得出大小关系”的思路一样,大家有兴趣的可以百度,这里就不提供思路了
AC代码:
#include<bits/stdc++.h>using namespace std;char s[29], ans[29];int cmp['Z'+5]['Z'+5];int cnt = 0, QQ = 1;bool cmp_user(const char a, const char b) {char cp;if(cmp[a][b]==-1) {printf("? %c %c\n", a, b);fflush(stdout);scanf(" %c", &cp);if(cp=='>') {cmp[a][b] = true;cmp[b][a] = false;return true;}else {cmp[a][b] = false;cmp[b][a] = true;return false;}}else return cmp[a][b];}void ins2(char c) {if(cmp_user(c, s[1])) {if(cmp_user(c, s[2])) s[3] = c;else s[3] = s[2], s[2] = c;} else {if(cmp_user(c, s[0])) {s[3] = s[2];s[2] = s[1];s[1] = c;} else {s[3] = s[2];s[2] = s[1];s[1] = s[0];s[0] = c;}}}void ins(char c) {int l = 0, r = cnt;while(l<r) {int mid = l+r>>1;if(cmp_user(c, ans[mid])) l = mid+1;else r = mid;}cnt ++;if(cmp_user(c, ans[r])) r ++;for(int i=cnt; i>=r+1; i--) ans[i] = ans[i-1];ans[r] = c;}int main() {int N, Q;scanf("%d%d", &N, &Q);for(int i=0; i<26; i++) s[i] = (char)(i+'A');s[N] = '\0';if(N==26) {memset(cmp, -1, sizeof(cmp));cnt = 0;ans[0] = s[0];ans[N] = '\0';for(int i=1; i<N; i++) ins(s[i]);printf("! %s\n", ans);} else {memset(cmp, -1, sizeof(cmp));if(cmp_user(s[0], s[1])) swap(s[0], s[1]);if(cmp_user(s[2], s[3])) swap(s[2], s[3]);if(cmp_user(s[1], s[3])) {swap(s[0], s[2]);swap(s[1], s[3]);}char x = s[2];if(cmp_user(s[4], s[1])) {if(cmp_user(s[4], s[3])) {s[2] = s[3];ins2(x);} else {s[2] = s[4];s[4] = s[3];ins2(x);}} else {if(cmp_user(s[4], s[0])) {s[2] = s[1];s[1] = s[4];s[4] = s[3];ins2(x);} else {s[2] = s[1];s[1] = s[0];s[0] = s[4];s[4] = s[3];ins2(x);}}printf("! %s\n", s);}//system("PAUSE");}

原创粉丝点击