题目1468:Sharing
求两个单词的共同后缀具体参见
http://ac.jobdu.com/problem.php?pid=1468
算法分析
把两个单词右对齐,然后从短的单词开始和长的单词的对应位置进行比较
如下两个单词,loading的长度为7,ending的长度为6,
则loading从第2个位置开始,ending从第1个位置开始依次比较。
L o a d i n g
e n d i n g
需要注意的是
1.输入格式 printf("%05d\n",one);
2.将长单词的起始开始位置向右移动dis位,然后逐对比较。 dis为长单词的长度和短单词长度的差
while(dis>0){
one = toAdr[one];
dis--;
}
while(one!=two){
one = toAdr[one];
two = toAdr[two];
}
源程序
// Name : judo1468.cpp
// Author : wdy
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int toAdr[100001] = {0};
void init(int N){
memset(toAdr,0,sizeof(toAdr));
int from;
char c;
int to;
for(int i = 0;i<N;i++){
scanf("%d %c %d",&from,&c,&to);
toAdr[from] = to;
}
}
int getLength(int beg){
int from = beg;
int len=1;
while(toAdr[from]>0){
len++;
from = toAdr[from];
}
return len;
}
void findSuffix(int longWord,int shortWord,int dis){
int one = longWord;
int two = shortWord;
while(dis>0){
one = toAdr[one];
dis--;
}
while(one!=two){
one = toAdr[one];
two = toAdr[two];
}
if(one==-1)
printf("-1\n");
else
printf("%05d\n",one);//ATTENTION
}
void judge(int begone,int begtwo,int n){
init(n);
int len1 = getLength(begone);
int len2 = getLength(begtwo);
//std::cout<<"len1"<<getLength(begone);
//std::cout<<" len2"<<getLength(begtwo)<<std::endl;
if(len1>len2){
findSuffix(begone,begtwo,len1-len2);
}else{
findSuffix(begtwo,begone,len2-len1);
}
}
void judo(){
int one;
int two;
int n;
while(std::cin>>one>>two>>n){
judge(one, two, n);
}
}
int main() {
//cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
judo();
return 0;
}
/**************************************************************
Problem: 1468
User: KES
Language: C++
Result: Accepted
Time:190 ms
Memory:1908 kb
****************************************************************/