去哪儿0401在线笔试官方题解
发布于 2017-04-01 21:22 7859 次浏览 0 赞 最后一次编辑是 2017-04-01 21:27 来自 试题交流  

Hi,大家好,我是Gibbon,感谢同学们这么晚还坚持来看题解,对于同学们的求知精神,我仿佛又看到了当年自己求职的那一幕~欢迎大家选择并加入去哪儿!

 

在我的个人介绍中,HR姐姐给我扣上了全栈的帽子,感觉亚历山大,但本人还是更专注于后端开发的工作。所以,今天的题解我还是主要给大家进行后端开发的答疑,前端测试的编程题题解在下面的真题链接中有详细说明,同学们可以进行查看,请同学们理解~


废话不多说,进入正题,以下是编程题的真题链接:

按层打印二叉树:http://exercise.acmcoder.com/online/online_judge_ques?ques_id=4172&konwledgeId=169 

单词变换:http://exercise.acmcoder.com/online/online_judge_ques?ques_id=4378&konwledgeId=169 

进制转换:http://exercise.acmcoder.com/online/online_judge_ques?ques_id=4377&konwledgeId=169 

酒店评分:http://exercise.acmcoder.com/online/online_judge_ques?ques_id=4382&konwledgeId=169 

 

1. 按层打印二叉树

解题思路:根据输入的前序和中序遍历结果唯一重构一颗二叉树,然后借用队列实现按层打印。

示例代码:

package main

import (
"bufio"
"container/list"
"fmt"
"os"
"strconv"
"strings"
)

type Node struct {
left  *Node
right *Node
data  int
}

type Queue list.List

func NewQueue() *Queue {
q := list.New()
return (*Queue)(q)
}

func (q *Queue) Push(node *Node) {
(*list.List)(q).PushBack(node)
}

func (q *Queue) Pop() *Node {
e := (*list.List)(q).Front()
(*list.List)(q).Remove(e)
return e.Value.(*Node)
}

func (q *Queue) Len() int {
return (*list.List)(q).Len()
}

func NewNode(v int) *Node {
return &Node{data: v}
}

func createBTree(pOrder, mOrder []int) *Node {
if len(pOrder) == 0 || len(mOrder) == 0 {
return nil
}

v := pOrder[0]
root := NewNode(v)
i := 0
for ; i < len(mOrder); i++ {
if v == mOrder[i] {
break
}
}

root.left = createBTree(pOrder[1:i+1], mOrder[:i])
root.right = createBTree(pOrder[i+1:], mOrder[i+1:])

return root
}

func levelPrint(root *Node) {
if root == nil {
return
}

q := NewQueue()
q.Push(root)
nextCnt := 1

first := true
for q.Len() != 0 {
curCnt := nextCnt
nextCnt = 0
for ; curCnt > 0; curCnt-- {
node := q.Pop()
if node.left != nil {
q.Push(node.left)
nextCnt += 1
}
if node.right != nil {
q.Push(node.right)
nextCnt += 1
}
if first {
first = false
} else {
fmt.Printf(" ")
}
fmt.Printf("%d", node.data)
}
}
}

func parse(str string) []int {
ss := strings.Split(str, " ")

var m []int
for _, s := range ss {
if len(s) != 0 {
n, _ := strconv.Atoi(s)
m = append(m, n)
}
}
return m
}

func main() {
r := bufio.NewReader(os.Stdin)
r.ReadLine()
line1, _, _ := r.ReadLine()
pOrder := parse(string(line1))

line2, _, _ := r.ReadLine()
mOrder := parse(string(line2))

root := createBTree(pOrder, mOrder)
levelPrint(root)
}

2. 单词变换

寻找最短路径相关算法。一种解题思路为:

以初始单词A为起点,找出单词列表D中所有满足变化规则的单词,构成列表A‘;再以A’中的单词为起点,找到单词列表(D-A‘)中满足变换规则的单词A‘’……,直到到达最终单词B,统计变换最短的路径长度。有点类似于树的层序遍历搜索。

示例代码:

# -*- coding: utf-8 *-*

# 题目描述
# 有一个单词列表,一个初始单词和一个最终单词,初始单词需要通过单词列表逐步变换到最终单词,求变换所需的最短变换路径长度
# 变换规则:每次只能变动1个字母(不可交换位置,如:从abc变成cad属于变动了2个字母),每次变换只能从单词列表中选取
# 例如:初始单词hot,最终单词dog,单词列表[got, god, dog, lot, log],最短变换路径为[hot,dot,dog],最短变换路径长度为3
# 注:单词列表中包含最终单词,不包含初始单词;列表中每一项单词长度与初始单词、最终单词相同;列表中单词不重复

def check(start, end, keywords):
	start_list = list(start)
	result = []
	min_count = len(keywords) + 1
	min_count = _next(list(start), end, min_count, 1, keywords, [])
	return min_count

def _next(start, end, min_count, count, keywords, steps):
	if count == min_count:
		# print '---too long %s---' % min_count
		return min_count
	if ''.join(start) == end:
		# print '[lucky]'
		# print steps
		# print '[lucky]'
		return count
	for i in xrange(0, len(keywords)):
		item = list(keywords[i])
		d = _diffrernce(start, item)
		if d == 1:
			flag = True
			new_keywords = keywords[:]
			new_keywords.remove(keywords[i])
			new_steps = steps[:]
			new_steps.append(keywords[i])
			# print new_keywords, item, count
			result = _next(item, end, min_count, count + 1, new_keywords, new_steps)
			min_count = result if result < min_count else min_count
	return min_count


def _diffrernce(a, b):
	count = 0
	for i in xrange(0, len(a)):
		if a[i] != b[i]:
			count += 1
	return count


if __name__ == '__main__':
	# result = check('hot', 'dog', ['dot', 'god', 'dog', 'lot', 'got', 'log'])
	# result = check('hot', 'dog', ['got', 'god', 'dog', 'lot', 'log'])
	import sys
	start = sys.stdin.readline().replace('\r\n', '').replace('\n', '')
	end = sys.stdin.readline().replace('\r\n', '').replace('\n', '')
	words = sys.stdin.readline().replace('\r\n', '').replace('\n', '').split(' ')
	result = check(start, end, words)
	print result

3. 进制转换

解题思路:

a-z的ascii是一个递增的uchar类型, 所以a-z对应到0-26的简单方法是减去a的ascii值,然后按照26进制的幂计算方式计算出对应的10进制值。

示例代码:

import sys

base = ord('a')

def convert(line):
numArr = [ord(c) - base for c in line]
numArr.reverse()
s = 0
for (i, n) in enumerate(numArr):
# print i, n
s += (n * (26 ** i))

return s
pass

if __name__ == '__main__':
line = sys.stdin.readline()
while len(line) > 0:
line = line.replace('\r\n', '').replace('\n', '')

print convert(line)
line = sys.stdin.readline()
pass

同学们还有其他疑问可以在下面留言,我会尽快进行答疑。再次诚挚邀请同学们加入去哪儿!


53 条回复

酒店评分求标程

2017-04-01 21:28

第一道题在本地编译器上都可以,移过去通过率就是0,浪费了好长时间还是没弄出来,就是在阅卷的时候能不能看一下代码,而不是只看结果。赛马网的编译器需改进了

2017-04-01 21:31
1

单词那个题 遍历的过程中(一层层往外扩) 需要保证每个单词只被遍历一次吗     

2017-04-01 21:31

是否通过是取笔试分数线以上的人的还是取前几名?

2017-04-01 21:31
小码快跑 回复 acmcoderWCCDu5BW

阅卷官都会看看同学们的代码思路和规范性的~

2017-04-01 21:32

第一题!!!本地通过,提交一直RE的同学有没有!把我顶上去

2017-04-01 21:33
2
Gibbon 回复 coder_6NNAU3QC

题目需要得到最短路径。遍历和是否计数没有关系,具体看你的解题逻辑了

2017-04-01 21:33

我只想问 A两道还有希望吗😂

2017-04-01 21:33
1
Gibbon 回复 coder_WNWP2TN9

因为有2套题,能说一下第二题是什么问题么?

2017-04-01 21:38
coder_6NNAU3QC 回复 Gibbon

那就奇怪了 我就是在层次遍历的过程中 通过Set 保证每个单词不会被重复遍历  最后通过率为0(给的用例能跑出正确结果)   并且之前刷leetcode上的这个题(https://leetcode.com/problems/word-ladder-ii/#/description) 过不去的用例中  好像是   有的单词不止被访问一次

2017-04-01 21:38

求酒店评分

2017-04-01 21:38

同求酒店评分为何很多人卡在20%

2017-04-01 21:39

前端编程题中的酒店评分,下面代码思路基本正确,但是只通过了20%,不知道哪里没有处理好,可以帮忙看看吗?

#include<iostream>
#include <algorithm>
using namespace std;
typedef struct Hotel
{
	int num;
    int min;
    float avage;
}h;
h hotel[10000];

bool cmpare(const h &a, const h &b){
     if(a.min > b.min){
     	//最低星级比较高的
     	return true;
     }else if(a.min == b.min){
    	//最低星级相等
    	if(a.avage > b.avage) {
    		//平均星级较高
    		return true;
    	}else if(a.avage == b.avage){
    		//平均星级相等
    		return a.num < b.num;
		} else{
			//平均星级较低
			return false;
		}
    }else{
    	//最低星级比较低
    	return false;
    }
    return false;
}

int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		int sum = 0;
		int min = 5;
		int tmp;
		for(int i=0;i<5;i++){
			cin>>tmp;
			sum += tmp;
			if(min > tmp){
				min = tmp;
			}
		}
		h htmp;
		htmp.num = i;
		htmp.min = min;
		htmp.avage = (float)sum / 5;
		hotel[i] = htmp;
	}
	sort(hotel,hotel+n,cmpare);
	
	for(int i=0;i<n;i++){
		cout<<hotel[i].num<<" ";
	}
	return 0;
}


2017-04-01 21:39

再给我10秒,二叉树层次遍历就AC了啊。。。然而就差了这十秒,电脑卡了。。coppy不上去啊拙计死了。。。

2017-04-01 21:42
1
Gibbon 回复 coder_6NNAU3QC

在寻找最短路径的过程中,一个单词可能被遍历多次,但是在一个最短路径中,一个单词只会出现一次吧。这个逻辑没问题吧

2017-04-01 21:43
coder_5726XYD3 回复 acmcoderqaP4grx0

我猜是因为你结果用的是int类型的,20%的测试用例数据太大,超出int最大值了。。。

2017-04-01 21:47

本地答案都是对的,至少几个测试用例都可以。提交就0%。输出格式到底是什么?进制转换那个不应该一个输入一个输出吗?第二题二叉树的,为什么本地也是对的,本地至少测试了45个啊,提交就提示我输出超限?多了个空格还是换行符?题这么简单让人把时间都浪费在输出格式上?!很难让人信服!

2017-04-01 21:47

为什么本地结果都对,提交后通过率只有80%?

2017-04-01 21:50

进制转换输入方式写成了如果输入空行则停止循环,把数据存到数组再把数组输出,内容正确但结果通过率0%...这种情况是不是就没分了

2017-04-01 21:50
coder_6NNAU3QC 回复 coder_GWDF7WVP

第二题吧 我换成long 就100%了

2017-04-01 21:52
coder_6NNAU3QC 回复 Gibbon

感觉没问题 我再好好研究下

2017-04-01 21:53

酒店第二道题只能跑20%,求解,以下是code

var count = +read_line();
var account = [];
        for (var i = 0; i < count; i++) {
            var item = read_line().split(' ');

            // int
            item.forEach(function (ele, ind) {
                item[ind] = +ele;
            });

            var min = Math.min.apply(null, item);

            var sum = 0;
            var j, len = item.length;
            for (j = 0; j < len; j++) {
                sum += +(item[j]);
            }
            var avg = (sum / count).toFixed(4);

            var obj = {};
            obj.index = i;
            obj.min = min;
            obj.avg = +avg;

            account.push(obj);
        }

        account.sort(function (a, b) {
            var aMin = a['min'], bMin = b['min'];
            var aAvg = a['avg'], bAvg = b['avg'];
            var aIndex = a['index'], bIndex = b['index'];
//            console.log(account);
            if (aMin !== bMin) {
                return bMin - aMin;
            } else {
                if (aAvg !== bAvg) {
                    return bAvg - aAvg;
                } else {
                    return aIndex - bIndex;
                }
            }
        });

        var finalArr = [];
        account.forEach(function (ele) {
            finalArr.push(ele.index);
        });
        print(finalArr.join(' '));


2017-04-01 21:55
Gibbon 回复 coder_DPPVHCTG

cat sample.in | python main.py 你是用这种方式来测试的么?

2017-04-01 21:57
Gibbon 回复 coder_Z2F3WVUA
# gibbon @ gibbon in ~/transcend/Dev-A/dev.2.按层打印二叉树/3.gocode [21:59:27]
$ cat ../2.inout/1.in
10
5 2 1 3 4 7 6 9 8 10
1 2 3 4 5 6 7 8 9 10
# gibbon @ gibbon in ~/transcend/Dev-A/dev.2.按层打印二叉树/3.gocode [21:59:38]
$ cat ../2.inout/1.in | ./3.gocode
5 2 7 1 3 6 9 4 8 10

我这里是这么测试的

2017-04-01 21:58

粗心大意害死人啊,交卷半小时,改对两道题……

第一题一开始还写了个堆,写了一半才想起空间会爆炸,耽误了好久- -

1.

#include<stdio.h>
#include<stdlib.h>
#define LEFT 0
#define RIGHT 1

struct Node{
	struct Node* left = NULL;
	struct Node* right = NULL;
	int value;
};
typedef struct Node BinTree;

int preorder[1001] = { 0 };
int inorder[1001] = { 0 };

struct Node* AddNode(struct Node* node, struct Node* root, int pos)
{
	if (pos == LEFT)
		root->left = node;
	if (pos == RIGHT)
		root->right = node;
	return node;
}
struct Node* ConstructBinTree(int* preorder, int* inorder, int size)
{
	int i;
	struct Node* root = (struct Node*)malloc(sizeof(struct Node));
	root->left = NULL;
	root->right = NULL;
	root->value = preorder[0];
	if (size == 1)
		return root;
	for (i = 0; i < size; i++)
	{
		if (inorder[i] == preorder[0])
			break;
	}
	if (i>0 && *(preorder + 1) != 0) //这两个地方没考虑
	  AddNode(ConstructBinTree(preorder + 1, inorder, i), root, LEFT); 
	if (i<size - 1 && *(preorder + i + 1) != 0 
        && *(inorder + i + 1) != 0) //这两个地方没考虑
	  AddNode(ConstructBinTree(preorder+i+1, inorder+i+1, size-i-1), root, RIGHT);
	return root;
}
void FloorTraverse(BinTree* tree)
{
	int front = 0;
	int rear = 0;
	struct Node* queue[10000];
	struct Node* tempNode;
	if (tree != NULL){
		queue[rear++] = tree;
		while (front != rear){
			tempNode = queue[front++];
			if (tempNode->left != NULL)
				queue[rear++] = tempNode->left;
			if (tempNode->right != NULL)
				queue[rear++] = tempNode->right;
			printf("%d ", tempNode->value);
		}
	}
}
int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
		scanf("%d", &preorder[i]);
	for (int i = 0; i < n; i++)
		scanf("%d", &inorder[i]);
	BinTree* tree = ConstructBinTree(preorder, inorder, n);
	FloorTraverse(tree);
	return 0;
}

2.
#include<stdio.h>
#include<string.h>
char num26[10000];

long long pow(long long a, long long b)
{
	if (b == 0)
		return 1;
	if (b == 1)
		return a;
	if (b == 2)
		return a*a;
	if (b % 2)
		return pow(pow(a, b / 2), 2)*a;
	else
		return pow(pow(a, b / 2), 2);
}

int main()
{
	long long result;
	while (scanf("%s", num26) != EOF)
	{
		result = 0;
		int length = strlen(num26);
		for (int i = 0; i < length; i++)
			result += (num26[i] - 'a')*pow(26, length - i - 1);
		printf("%lld\n", result); //要用lld啊……
		memset(num26, 0, 10000 * sizeof(char));
	}
	return 0;
}


2017-04-01 21:59

大神用的什么语言?


2017-04-01 22:01
进制转换,测试时一直为80%,是我代码问题吗
import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		String output="";
		while(sc.hasNext()){
			String s = sc.nextLine();
			char[] ch = s.toCharArray();
			long sum=0;
			for(int i=0;i<ch.length;i++){
				int n = ch[i]-'a';
				sum=(long) (sum+n*Math.pow(26, ch.length-i-1));
			}
			output = output + sum+" ";
		}
		String[] sp = output.split(" ");
		for(String st:sp){
			System.out.println(st);
		}
	}
}


2017-04-01 22:01

智障了,写java的,第二次中间变量用了int,越界了,最后才发现,这时候就体现出python的好处了

2017-04-01 22:02

本地测试结果没错,怎么评0%呢


# include <iostream>
# include <stdio.h>
# include <math.h>
 using namespace std;

int main ()
{
    int n, m=0,i=0;
    char a[10];
    char c;
    int ans=0;

while(1)
{  
	do{
    	c=cin.get(); 
		a[i]=c;
		m++; 
		i++;
   }while(c!='\n');
	
    for(i=m-2;i>=0;i--)
        {
          n=a[i]-97;  
          ans=ans+n*pow(26,(m-2-i));
        }
     
	cout<<ans<<'\n';
	i=0;
	m=0;
	ans=0;
getchar();
}
    return 0;
}


2017-04-01 22:02
coder_WX44B676 回复 coder_DFRDUX3J

看上面链接给的正确答案,说是用快速排序,这个是不稳定的排序,不符合题目条件3,所以可能是答案有问题

2017-04-01 22:05
Gibbon 回复 acmcodereY7ZCIgq

我也很好奇, 不知道有没有大神出来回答一下呀

2017-04-01 22:06

看上面酒店评分链接给的正确答案,说是用快速排序,这个是不稳定的排序,不符合题目条件3,所以可能是答案有问题

更正:若新开O(n)空间,再将排序结果合并,则快速排序稳定;若使用in-place交换,则快速排序不稳定

2017-04-01 22:07
Gibbon 回复 coder_XVC565CJ

按照题目要求一次性会输入多行,所以需要用cin.eof()来进行判断

2017-04-01 22:12

第一题按层打印二叉树只对了20%,真心不懂

#include <bits/stdc++.h>
using namespace std;
class node{
public:
    int v;
    node *lchild;
    node *rchild;
    node(int value = 0){
        v = value;
        lchild = NULL;
        rchild = NULL;
    }
};
node* build(int a[], int as, int b[], int bs, int len){
    int temp = a[as];
    int i;
    for(i = bs; i < len; i++)
        if(b[i] == temp)
            break;
    node *head = new node(temp);
    if(i - bs >= 1)
        head->lchild = build(a, as + 1, b, bs, i - bs);
    if(len - (i - bs + 1) >= 1)
        head->rchild = build(a, as + i - bs + 1, b, i + 1, len - (i - bs + 1));
    return head;
}
void printTree(node *head){
    if(head == NULL)
        return;
    queue<node*> q;
    node *cur = head;
    q.push(cur);
    int flag = 1;
    while(!q.empty()){
        node *p = q.front();
        if(flag == 1){
            cout<<p->v;
            flag = 0;
        }
        else
            cout<<" "<<p->v;
        q.pop();
        if(p->lchild != NULL)
            q.push(p->lchild);
        if(p->rchild != NULL)
            q.push(p->rchild);
    }
}
int main()
{
    int n;
    cin>>n;
    int *a = new int[n];
    int *b = new int[n];
    for(int i = 0; i < n; i++)
        cin>>a[i];
    for(int i = 0; i < n; i++)
        cin>>b[i];
    node *head;
    head = build(a, 0, b, 0, n);
    printTree(head);
}


2017-04-01 22:16

求c++版。。。


2017-04-01 22:21
1

系统是不是有问题,如下,这是我看到的提交AC代码,首先没有头文件<math.h>,而且,给出的几个测试用例一个都通不过去,然后就AC了。。

#include<stdio.h>

#include<string.h>

int main()

{char s[10000];

while(scanf("%s",s)!=EOF)

{int n=strlen(s),i=0;long int z=0;

while(n-->0)

z+=(s[i++]-'a')*pow(26,n);

printf("%ld\n",z);

}

return 0;

}


2017-04-01 22:31

酒店的答案确定没有问题?为什么说我答案错误,我自己拿眼睛核对了。。。似乎没有问题啊?

2017-04-01 22:39
acmcoderARPiPeO7 回复 acmcoderr

同问,看了一遍,我也想知道为什么了。。。。另外前端卷子是都有这道题吗?我好像做错卷子了。。。

2017-04-01 22:45
coder_XVC565CJ 回复 Gibbon

可惜了 就因为这一点儿……

2017-04-01 22:46
coder_JT5SF6KJ 回复 coder_F8YQG95F
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String output="";
            String s = sc.nextLine();
            char[] ch = s.toCharArray();
            long sum=0;
            for(int i=0;i<ch.length;i++){
                int n = ch[i]-'a';
                sum=(long) (sum+n*Math.pow(26, ch.length-i-1));
            }
            output = output + sum;
            System.out.println(output);
        }
    }
}

为什么不这样来呢?得到一个输出一个

2017-04-01 23:12
coder_6NNAU3QC 回复 coder_6NNAU3QC

知道错在哪了 起始单词不在单词表中。。。。把这点忽略了

2017-04-01 23:23

两道AC,一道因为句尾多输出空格没过。。能过笔试么。。

2017-04-01 23:43
acmcoderr 回复 acmcoderARPiPeO7

我几个前端朋友都是考这题。可能随机分配的吧

2017-04-01 23:51
var n = ~~read_line()
var dlr = read_line().split(' ').filter(function(value){
	return value !== ''
})
var ldr = read_line().split(' ').filter(function(value){
	return value !== ''
})
function Tree(l, d, r){
	this.value = d
	this.left = l
	this.right = r
}
function getTree(_dlr, ldr){
	var dlr = _dlr.slice(0)
	if(dlr.length === 0) return null
	if(dlr.length === 1) return new Tree(null, dlr.shift(), null)
	var d = dlr.shift()
	var dindex = ldr.indexOf(d)
	var ldlr = dlr.slice(0, dindex)
	var rdlr = dlr.slice(dindex)
	var lldr = ldr.slice(0, dindex)
	var rldr = ldr.slice(dindex + 1)
	return new Tree(getTree(ldlr,lldr), d,getTree(rdlr,rldr))
}
function layer(tree){
	var queue = [tree]
	var node, re = ''
	while(node = queue.shift()){
		re += node.value + ' '
		if(node.left) queue.push(node.left)
		if(node.right) queue.push(node.right)
	}
	return re.slice(0, -1)
}
print(layer(getTree(dlr, ldr)))

二叉树层序遍历只能过60%   完全不知道为什么  感觉没有毛病

2017-04-02 00:11
//字符串转换那道题,就是hot dog那道
//我的代码在myeclipse环境运行没错,到了赛码网,一个数据都不通过
//希望您能看一下我的代码
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
int result=0;
Scanner sc = new Scanner(System.in);
   String s1 = sc.nextLine();
   String s2 = sc.nextLine();
   String s3 = sc.nextLine();
   String[] arr=s3.split(" ");
   //************
   char[] start=s1.toCharArray();
   char[] end=s2.toCharArray();
   char[][] ss=new char[arr.length][start.length];
   for(int m=0;m<arr.length;m++){
   ss[m]=arr[m].toCharArray();
   }
   //***********
  int start_dif=0;
  int[] difs=new int[arr.length];
  //初始化start_dif
  for(int i=0;i<start.length;i++){
  if(start[i]!=end[i]){
  start_dif++;
  }
  }
  //初始化difs
  for(int m=0;m<arr.length;m++){
  int count=0;
  for(int i=0;i<start.length;i++){
  if(ss[m][i]!=end[i]){
  count++;
  }
  }
  difs[m]=count;
  }
  //开始变换
  while(start_dif!=0){
//先找difs[i]=start_dif-1的
  ArrayList<Integer> list=new ArrayList<Integer>();
  for(int i=0;i<arr.length;i++){
  if(difs[i]==start_dif-1){
  list.add(i);
  }
  }
 //****************
  for(int i=0;i<list.size();i++){
  int difs_star=0;
  for(int m=0;m<start.length;m++){
  if(start[m]!=ss[list.get(i)][m]){
  difs_star++;
  }
  }
  if(difs_star==1){//只有一处不同,让start=ss[list.get(i)]
  for(int n=0;n<start.length;n++){
  start[n]=ss[list.get(i)][n];
  }
  start_dif--;
  result++;
  break;
  }
  }
  }
  System.out.println(result+1);
}
}

基本思想就是记录每个单词与目标单词的相同位置但字母不同的个数(起始单词不同个数为start_dif,其他单词不同个数为difs[]),每次在difs[]中找到比start_dif小1的单词,并转换成这个单词。

这样既能保证每次改变一位,又能向着目标单词转换。

2017-04-02 00:36
import java.lang.Math;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		
		HashMap<Character, Integer> hashMap=new HashMap<Character, Integer>();
		hashMap.put('a', 0);
		hashMap.put('b', 1);
		hashMap.put('c', 2);
		hashMap.put('d', 3);
		hashMap.put('e', 4);
		hashMap.put('f', 5);
		hashMap.put('g', 6);
		hashMap.put('h', 7);
		hashMap.put('i', 8);
		hashMap.put('j', 9);
		hashMap.put('k', 10);
		hashMap.put('l', 11);
		hashMap.put('m', 12);
		hashMap.put('n', 13);
		hashMap.put('o', 14);
		hashMap.put('p', 15);
		hashMap.put('q', 16);
		hashMap.put('r', 17);
		hashMap.put('s', 18);
		hashMap.put('t', 19);
		hashMap.put('u', 20);
		hashMap.put('v', 21);
		hashMap.put('w', 22);
		hashMap.put('x', 23);
		hashMap.put('y', 24);
		hashMap.put('z', 25);

		String s;
		ArrayList<Integer> list=new ArrayList<Integer>();

	

		int t=0;

		String lineString;
		ArrayList<String> arrayList=new ArrayList<String>();
		Scanner sc=new Scanner(System.in);
		while (!"".equals(lineString=sc.nextLine())) {
			arrayList.add(lineString);
		}	
		
		for (int i = 0; i < arrayList.size(); i++) {
			
		
	    
		char [] character=arrayList.get(t).toCharArray();

		int baby=0;
		
		for (int i1 = 0; i1 < character.length; i1++) {
			int[] sum = new int [character.length];
			sum[i1]=hashMap.get(character[i1]);
		    baby=baby+(int) (sum[i1]*Math.pow(26, character.length-1-i1));
		    
		}
		list.add(baby);
		

	System.out.println(list.get(t));
	t++;

		}
	}

		
}

进制转换那道题ac不了求指点

2017-04-02 00:40
acmcoderwgXWq74k 回复 acmcoderwgXWq74k

我才发现 赛码的js read_line()是读不了’0 1 2 3…1000’这样的1000个数据的 我把1000个数据考到本地运行结果数量和赛码完全不一样

2017-04-02 00:41
acmcoderwgXWq74k 回复 acmcoderwgXWq74k

核对了 结果是对的 赛码的问题

2017-04-02 01:38
acmcoderxQru71pr 回复 acmcoderr

一样的方法,同20%,不知道错在哪,求解答

2017-04-02 12:39
acmcoderBoRyd1uu 回复 acmcoderwgXWq74k

JS在1000的时候确实有问题,我的也只能过60%,然后报错误,本地用1000的测试数据跑,什么问题都没有。。。【924,106,964,14…】

2017-04-03 00:48

我在做去哪真题的时候在autopilot02题目(题目ID3838)的时候发现问题,他说我输出答案错误。。。但是我输出的路径确实是最短路径啊程序员哥哥能不能给下解答哪错了。。。


该数据运行结果错误:答案错误

输入:

0 0 1 0 0 0 1

1 0 1 0 1 0 0

0 0 1 0 0 1 0

0 1 1 1 0 1 0

0 0 0 0 0 1 0

0 1 1 0 1 1 0

0 0 1 0 1 0 0

输出:

0,0

0,1

1,1

2,1

2,0

3,0

4,0

4,1

4,2

4,3

4,4

3,4

2,4

2,3

1,3

0,3

0,4

0,5

1,5

1,6

2,6

3,6

4,6

5,6

6,6


2017-04-03 09:38
acmcoderLdGRIo1o 回复 coder_YBTEDATX

你在本地编译器试过了吗?

while (!"".equals(lineString=sc.nextLine())) {

arrayList.add(lineString);

}

这句如果没有键盘输入,会阻塞,怎么向下运行?


2017-04-03 09:39

进制转换那个题,用java写得,没有考虑类型,用的int。

字符串那个:hot dog那个,看例子与规则:

# 变换规则:每次只能变动1个字母(不可交换位置,如:从abc变成cad属于变动了2个字母),每次变换只能从单词列表中选取
# 例如:初始单词hot,最终单词dog,单词列表[got, god, dog, lot, log],最短变换路径为[hot,dot,dog],最短变换路径长度为3

真是一直不明白,最后路径中的dot是怎么从单词列表[got,god,dog,lot,log]中取出来的。

2017-04-06 10:45
添加回复
回到顶部