牛客网浙江大学机试--Sharing

题目: 牛客网链接

概述: 给出两个字符串,用链表来表示(不是严谨的链表,只是表示出每个节点的起始位置,和下一个节点位置)。让找两个字符串的公共节点。

思路: 就是用一个足够大的数组表示可能出现的地址,读取下一个地址,并将对应数组的值+1,当为2的时候就是前缀对应的地址。
当有出现两次的节点一定是公共节点。

我们在采用scanf输入字符的时候要考虑后面的空格或者回车,而采用cin却不会出现这样情况。但是我们为了节约运行时间,采用scanf用法,可以用个字符数组来解决这个问题。

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;

int nextPosition[100000]; //用来记录下一个位置
int countNum[100000]; //用来记录每个节点被引用的次数,当出现被引用两次的时候,就是公共节点的开始位置。 

int main()
{
	int firstStart, secondStart, n;
	while(scanf("%d%d%d", &firstStart, &secondStart, &n) != EOF)
	{

		fill(nextPosition, nextPosition+100000, 0);
		fill(countNum, countNum+100000, 0);
		char temp[2];
		int firstPosition, secondPosition;
		for(int i = 0; i < n; i++)
		{
			scanf("%d%s%d", &firstPosition, &temp ,&secondPosition);
			nextPosition[firstPosition] = secondPosition;
		}
		int position = firstStart;
		while(position != -1)
		{
			countNum[position]++;
			position = nextPosition[position];
		}
		
		int index = -1; //用来记录公共起始位置
		position = secondStart;
		while(position != -1)
		{
			countNum[position]++;
			if(countNum[position] == 2)
			{
				index = position;
				break;
			} 
			position = nextPosition[position]; 
		}
		printf("%d\n", index); 
	} 
	
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值