題目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[N];
string w[N];
int num[N];
int ID;
//map[i]存了i目錄下的所有文件信息,對應到了其ID
map<string, int>mop[N/2];
int n;
char ans[N]; 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中存放其文件夾中的子目錄的直接名稱。
這樣我們從根目錄一路走過來的時候,就可以當前的目錄編號,也相應知道其內的目錄個數啦。
然後每條數據處理一下就好~
*/