您的位置:首页 > Web前端

【[Offer收割]编程练习赛23 B】【map模拟】合并子目录

2017-08-20 14:40 489 查看


题目2 : 合并子目录

时间限制:10000ms
单点时限:1000ms
内存限制:256MB


描述

小Hi的电脑的文件系统中一共有N个文件,例如:
/hihocoder/offer23/solutions/p1
/hihocoder/challenge30/p1/test  
/game/moba/dota2/uninstall  
经过统计,小Hi认为他的电脑中子目录实在太多了,于是他决定减少子目录的数量。小Hi发现其中一些子目录只包含另一个子目录,例如/hihocoder/offer22只包含一个子目录solution,/game只包含一个子目录moba,而moba也只包含一个子目录dota2。小Hi决定把这样的子目录合并成一个子目录,并且将被合并的子目录的名字用'-'连起来作为新子目录的名字。合并之后上例的3个文件的路径会变为:
/hihocoder/offer23-solutions/p1 /hihocoder/challenge30-p1/test /game-moba-dota2/uninstall


输入

第一行包含一个整数N (1 ≤ N ≤ 10000)  
以下N行每行包含一个字符串,代表一个文件的绝对路径。保证路径从根目录"/"开始,并且文件名和目录名只包含小写字母和数字。  
对于80%的数据,N个文件的绝对路径长度之和不超过10000  
对于100%的数据,N个文件的绝对路径长度之和不超过500000


输出

对于输入中的每个文件,输出合并子目录之后该文件的绝对路径。

样例输入
3
/hihocoder/offer23/solutions/p1
/hihocoder/challenge30/p1/test
/game/moba/dota2/uninstall


样例输出
/hihocoder/offer23-solutions/p1
/hihocoder/challenge30-p1/test
/game-moba-dota2/uninstall


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<ctype.h>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
#include<sstream>
using namespace std;
void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); }
#define MS(x, y) memset(x, y, sizeof(x))
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b > a)a = b; }
template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b < a)a = b; }
const int N = 5e5 + 10, M = 0, Z = 1e9 + 7, inf = 0x3f3f3f3f;
template <class T1, class T2>inline void gadd(T1 &a, T2 b) { a = (a + b) % Z; }
int casenum, casei;
char s
;
string w
;
int num
;
int ID;
//map[i]存了i目录下的所有文件信息,对应到了其ID
map<string, int>mop[N/2];
int n;
char ans
; int P;
int main()
{
ID = 0;
scanf("%d", &n);
for (int nid = 1; nid <= n; ++nid)
{
scanf("%s", s);
for (int i = 0; s[i]; ++i)
{
if (s[i] == '/')s[i] = ' ';
}
w[nid] = s;
int now = 0;
stringstream cinn(s);
string ss;
while (cinn >> ss)
{
++num[nid];
if (!mop[now].count(ss))
{
mop[now][ss] = ++ID;
}
now = mop[now][ss];
}
}
for (int nid = 1; nid <= n; ++nid)
{
int now = 0;
stringstream cinn(w[nid]);
string ss;
P = 0;
while (cinn >> ss)
{
--num[nid];
if (num[nid] && mop[now].size() == 1 && P)
{
int sz = ss.size();
ans[P++] = '-';
for (int j = 0; j < sz; ++j)ans[P++] = ss[j];
}
else
{
int sz = ss.size();
ans[P++] = '/';
for (int j = 0; j < sz; ++j)ans[P++] = ss[j];
}
now = mop[now][ss];
}
ans[P] = 0;
puts(ans);
}
return 0;
}
/*
【trick&&吐槽】
string还是慢呀,尤其是+操作。

【题意】
我们希望合并嵌套关系的文件目录的名称。
如果对于一个目录文件,其下只有一个目录文件,那这2个目录文件之间要合并。
让你输出在所有目录文件合并之后,每个文件的名称。

【分析】
这种字符串的嵌套任务我们怎么处理? 用map。
我们设想为文件夹设个map,map中存放其文件夹中的子目录的直接名称。
这样我们从根目录一路走过来的时候,就可以当前的目录编号,也相应知道其内的目录个数啦。
然后每条数据处理一下就好~

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息