九度笔记之 1468:Sharing

题目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
****************************************************************/






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值