Kurniady Systems - Tools
Viewing Text Document
Title:
INC 2008 Qual C
Owner: Andrian Kurniady
Last updated on: Tuesday, 15 July 2008
Description:
My solution for INC 2008 qualification problem C. Got timelimit exceeded because it runs in 8 secs out of the 5 secs limit.
Content:
#include <string>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <deque>
#include <string.h>
using namespace std;
int chamap[1000];
char buffer[1500000];
inline pair<int,string> calc(string s){
pair<int,string> res;
res.first=0;
res.second=s;
for (int i=0;i<s.size();i++){
res.first+=chamap[s[i]];
}
return res;
}
inline pair<pair<int,string>,pair<int,string> > potong(pair<int,string> s, int len){
pair<int,string> left, right;
int ulen = 0;
for (int i=0;i<s.second.length();i++){
if (ulen+chamap[s.second[i]]+1>len){
left.second = s.second.substr(0,i)+"-";
right.second = s.second.substr(i);
left.first = ulen+1;
right.first = s.first-ulen;
break;
} else {
ulen += chamap[s.second[i]];
}
}
return make_pair(left, right);
}
inline deque<pair<int,string> > calc2(string s){
deque<pair<int,string> > res;
if (s==""){
res.push_back(make_pair(0,""));
return res;
} else {
string last = "";
for (int i=0;i<s.size();i++){
if (s[i]==' '){
if (last!=""){
res.push_back(calc(last));
last = "";
}
res.push_back(calc(" "));
} else {
last = last + s[i];
}
}
if (last!=""){
res.push_back(calc(last));
}
return res;
}
}
int main(){
int width;
int tc=0;
while (scanf("%d", &width)!=EOF){
memset(chamap, 0, sizeof(chamap));
gets(buffer);
while (true) {
gets(buffer);
if (!strcmp(buffer, "END OF LIST"))
break;
char buf[10];
int x;
sscanf(buffer+1, "%d", &x);
chamap[buffer[0]] = x;
}
string last = "";
int lus=0;
vector<string> semua;
while (true){
gets(buffer);
if (!strcmp(buffer, "END OF FILE"))
break;
last = last + buffer;
lus=1;
int rep=0;
do {
rep=0;
for (int i=0;i+1<last.size();i++){
if (last[i]=='\\' && last[i+1]=='n'){
semua.push_back(last.substr(0,i));
last = last.substr(i+2);
rep=1;
break;
}
}
} while (rep);
}
semua.push_back(last);
printf("Case #%d:\n", ++tc);
for (int lin=0;lin<semua.size();lin++){
deque<pair<int,string> > tokens = calc2(semua[lin]);
int usedlength=0;
while (tokens.size()){
pair<int,string> front = tokens.front(); tokens.pop_front();
if (usedlength==0){
// first word
if (front.first>width){
// break it
pair<pair<int,string>,pair<int,string> > potongan = potong(front, width);
printf("%s", potongan.first.second.c_str());
usedlength=0;
puts("");
tokens.push_front(potongan.second);
} else {
// fit!
usedlength = front.first;
printf("%s", front.second.c_str());
}
} else {
if (usedlength+front.first>width){
// second word not fit
usedlength=0;
puts("");
tokens.push_front(front);
} else {
// second word fit!
printf("%s", front.second.c_str());
usedlength+=front.first;
}
}
}
puts("");
}
}
return 0;
}
Please note that the document shown may be copyrighted.
Please contact the owner of this document for the details.
Valid XHTML and CSS. Powered by Ruby on Rails.