USACO 1.4 The Clocks (位操作+枚举+DFS)

本文深入探讨了在编程领域中应用复杂算法与数据结构的策略与实践,包括排序算法、动态规划、哈希算法等核心概念,旨在帮助开发者优化代码性能,解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#define DEBUG 1
#define TESTCASES 9
#define INF (1 << 31 - 1)
#define CLOCKS 9
#define MOVES 9

int arrayOfMoves[MOVES + 1] = {0, 18911232, 19136512, 2363904, 16810048, 2134536, 262657, 36936, 73, 4617};
int set = 57521883;
int minTurns;
int finalSequence;

void turnDials(int state, int move, int numOfTurns, int sequence){
	if (numOfTurns > minTurns)
		return;

	if (move > MOVES){
		if (state == 0){
			if (numOfTurns < minTurns){
				minTurns = numOfTurns;
				finalSequence = sequence;
			} else if (sequence > finalSequence)
				finalSequence = sequence;
		}
		return;
	}

	int timesOfMove;
	for (timesOfMove = 0; timesOfMove <= 3; timesOfMove++){
		int newState = (state + arrayOfMoves[move] * timesOfMove) & set;
		//移位操作符优先级很低,注意加上各种括号
		int newSequence = sequence + (timesOfMove << (2 * (MOVES - move)));
		turnDials(newState, move + 1, numOfTurns + timesOfMove, newSequence);
	}
}

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "inputx.txt";
		inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif
	
	int initialState = 0;
	int clock;
	for (clock = 1; clock <= CLOCKS; clock++){
		int colckState;
		scanf("%d", &colckState);
		initialState = (initialState << 3) + (colckState / 3 % 4);
	}

	minTurns = 28;
	finalSequence = 0;
	turnDials(initialState, 1, 0, 0);

	int move;
	for (move = 1; move <= MOVES; move++){
		int timesOfMove = ( finalSequence >> (2 * (MOVES - move) ) ) & 3;
		while (timesOfMove-- > 0){
			printf("%d%c", move, minTurns == 1 ? '\n' : ' ');
			minTurns--;
		}
	}

#if DEBUG
	}
#endif
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值