題意:給多組字符串每組字符串代表一個目錄,最後一個名字代表書名,遇到0結束並輸出處理後的目錄,處理規則是同層同樣的類別按照字典序輸出,先輸出目錄再輸出書名,並且要按照層次輸出
2016ICPC北京網賽第一題
題意讀懂之後這道題就變成了一個簡單的模擬,模擬所用的結構跟鏈表類似,最簡單的處理方式是把目錄和書名開兩個vector來儲存,輸出的時候遞歸輸出即可
代碼如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<iostream>
#include<string>
using namespace std;
const int maxn = 107;
char s[maxn];
struct Node
{
string name;
vector<Node> book,cate;
bool operator < (const Node &r) const
{
return name < r.name;
}
};
vector<Node> root;
int findd(vector<Node> &v,Node x)
{
for(int i=0; i<v.size(); i++)
if(v[i].name == x.name) return i;
return -1;
}
void output(vector<Node> &v,int dep)
{
sort(v.begin(),v.end());
for(int i=0; i<v.size(); i++)
{
for(int j=0; j<4*dep; j++) printf(" ");
printf("%s\n",v[i].name.c_str());
output(v[i].cate,dep+1);
sort(v[i].book.begin(),v[i].book.end());
for(int j=0; j<v[i].book.size(); j++)
{
for(int k=0; k<4*(dep+1); k++) printf(" ");
printf("%s\n",v[i].book[j].name.c_str());
}
}
}
int main()
{
int kas=0;
while(gets(s))
{
if(s[0]=='0' && s[1] == '\0')
{
printf("Case %d:\n",++kas);
output(root,0);
root.clear();
}
else
{
int len=strlen(s);
string t="";
int i=0;
for(; i<len; i++)
{
if(s[i] == '/') break;
t += s[i];
}
Node x;
x.name=t;
int pos=findd(root,x);
if(-1 == pos)
{
root.push_back(x);
pos=root.size()-1;
}
Node *now = &root[pos];
t="";
i++;
for(; i<len; i++)
{
if(i == len-1)
{
t+=s[i];
break;
}
if(s[i] == '/')
{
x.name=t;
int pos=findd(now->cate,x);
if(-1 == pos)
{
now->cate.push_back(x);
pos=now->cate.size()-1;
}
now = &now->cate[pos];
t="";
}
else t+=s[i];
}
x.name=t;
pos=findd(now->book,x);
if(-1 == pos)
{
now->book.push_back(x);
pos=now->book.size()-1;
}
}
}
return 0;
}