题意:
有一个形似央视大楼的筒,从A口可以放球,放进去的球可通过挡板DE使其掉进B管或C管里,现有带1-10标号的球按给定顺序从A口放入,问是否有一种控制挡板的策略可以使B管和C管中的球从下往上标号递增。
输入:第一行输入数据组数N。接下来N行为N组具体数据,每组数据中有10个整数,代表球的放入顺序。
输出:
对于每组数据,若策略存在,输出YES;若不存在,输出NO。
思路:用二进制枚举或DFS均可。
DFS:写法
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <assert.h>
#include <time.h>
typedef long long LL;
const int INF = 500000001;
const double EPS = 1e-9;
const double PI = acos(-1.0);
using namespace std;
int N;
int a[100];
int lleft[100], rright[100];
bool dfs(int deep, int len_left, int len_right)
{
if(deep != 0 && (len_left >= 2 && (lleft[len_left-1] <= lleft[len_left-2]) ||
(len_right >= 2 && rright[len_right-1] <= rright[len_right-2])))
{
return false;
}
if(deep == 10)
{
return true;
}
if(deep < 10)
{
lleft[len_left] = a[deep];
if(dfs(deep+1, len_left+1, len_right)) return true;
rright[len_right] = a[deep];
if(dfs(deep+1, len_left, len_right+1)) return true;
}
return false;
}
int main()
{
//freopen("test0.in", "r", stdin);
//freopen("test0.out", "w", stdout);
//srand(time(NULL));
while(~scanf("%d", &N))
{
for(int i = 0; i < N; i++)
{
for(int j = 0; j < 10; j++)
scanf("%d", &a[j]);
if(dfs(0, 0, 0))
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
枚举二进制写法:
主要利用10位数的二进制特性:从0000000000 -- 1111111111
当二进制的某位为0表示将小球放在C管里,否则将当前的小球放在B管里。
1111111111 转换为十进制是2^10-1。从0~2^10-1的过程,就枚举了每个管里可能的所有组合情况。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <assert.h>
#include <time.h>
typedef long long LL;
const int INF = 500000001;
const double EPS = 1e-9;
const double PI = acos(-1.0);
using namespace std;
int N;
int a[100];
int lleft[100], rright[100], flag;
int main()
{
//freopen("test0.in", "r", stdin);
//freopen("test0.out", "w", stdout);
//srand(time(NULL));
while(~scanf("%d", &N))
{
for(int i = 0; i < N; i++)
{
for(int j = 0; j < 10; j++)
scanf("%d", &a[j]);
for(int j = 0; j < 1<<10; ++j)
{
int len_left = 0, len_right = 0;
flag = 1;
for(int k = 1, cnt = 0; k < 1<<10; k<<=1, cnt++)
{
if(j & k)
{
lleft[len_left++] = a[cnt];
}
else
{
rright[len_right++] = a[cnt];
}
if((len_left >= 2 && lleft[len_left-1] <= lleft[len_left-2]) ||
(len_right >= 2 && rright[len_right-1] <= rright[len_right-2]))
{
flag = 0;
break;
}
}
if(flag)
{
break;
}
}
if(flag)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
return 0;
}