Common BoardНарод, кто может указать на часть моего кода которая тормозит алгоритм? Чистил как мог, не смог выйти за 0.125 секунд import java.util.Scanner; public class Timus { public static void main (String[] args) { Scanner in = new Scanner(System.in);
byte m = in.nextByte(), n = in.nextByte();
System.out.println( (m*n-1)%2==0 ? "[second]=:]" : "[:=[first]");
in.close();
} } Всё нормально, просто джава медленная. Вон у вас задача a+b за 0.109. Спасибо за пояснение;) а каким же образом люди в топе выходят за 0.05 секунд? Вон первое место в А+B аж за 0.015 работает! Наверняка люди обходят стороной медленные методы и операции. Может вы знаете ресурс где можно почитать об этом? Поиск в гугле ни привёл ни к чем К сожалению, не могу сказать точно. Тут есть несколько моментов. Во-первых, более ранняя джава была быстрее, что можно увидеть по тому, что в основном большинство сабмитов, где указано java 1.5 / java 1.6, быстрее, чем те, в которых java 1.8. Конечно, этот сабмит а+б за 0.015 как раз на джаве 1.8, для меня это конечно странно. Может в коде в опциях был выставлен какой-то ключ для использования более ранней версии или типа того... Во-вторых, "общий" совет, который я могу дать — используйте BufferedReader (и если надо, StreamTokenizer) вместо Scanner'a, потому что последний в джаве обычно медленнее. (см. также код внизу страницы http://acm.timus.ru/help.aspx?topic=java&locale=ru). Хотя, конечно, для программ с маленьким объёмом входных данных разница не должна быть сильно критичной, но там где надо считывать со входа мегабайты — она очень ощутима. If the matrix size is 3, with the given contraints, it won't be "2 special cells", because 8 of them will be walls, and will be only one free cell. Could be that those special cells were located at the same place? Please drop some light on that. Thanks looks like someone has found a special case here ;) either 3x4 or 4x3 has two points, 3x3 does not using System; using System.Collections.Generic; using System.Linq; using System.Text; class Program { static void Main(string[] args) { int k; int n; do { do{ n = int.Parse(Console.ReadLine()); } while (!(n >= 2)); do { k = int.Parse(Console.ReadLine()); } while (!(k >= 2 && k <= 10)); } while (!(n + k <= 18)); int start = (int)Math.Pow(10, n - 1); int end = 0; int check = start; int BigCount = 0; for (int i = n - 1; i >= 0; i--) end += (k - 1) * (int)Math.Pow(10, i); int h = end - start + 1; int o = 0; for (int l = 0; l < n; l++) { o += h % 10 * (int)Math.Pow(k, l); h = h / 10; } for (int i = 0; i < o; i++) { int count = 0; double p = check; for (int j = 0; j < n / 2; j++) { if ((p % 10 + p / 10 % 10) > 0) count++; p = p / 100; } if (count != 0) BigCount++; check++; count = 0; p = check; int r = 0; int m = 0; for (int l = 0; l < n; l++) { if (p % 10 == k) { count++; m += (10 - k) * (int)Math.Pow(10, l); r = 10 - k; } p += r; p = (int)p / 10; } check += m; } Console.Write(BigCount); } } Норм решение? Edited by author 16.01.2017 04:29 Edited by author 16.01.2017 04:30 This is my code: #include <iostream> #include <cmath> using namespace std; int main() { int a[101], n, x, dis1 = 0, dis2 = 0, lb, rb; bool flag = false, flag2 = false;
cin >> n >> x;
if ((x == 0)) flag2 = true; else { if ( n == 0 ) flag = true; }
for ( int i = 0; i < n; i++ ) { cin >> a[i]; if ( (x > 0) && (a[i] < x) && (a[i] > 0) ) flag = true; if ( (x < 0) && (a[i] > x) && (a[i] < 0) ) flag = true; }
if (flag) cout << "Impossible" << endl; else { lb = a[0]; rb = a[0]; for ( int i = 1; i < n; i++ ) { if ( (a[i] > 0) && (a[i] > rb) && (a[i] > x) ) rb = a[i];
if ( (a[i] < 0) && (abs(a[i]) < abs(lb)) && (a[i] < x) ) lb = a[i]; }
if ( x > 0 ) { dis1 = x; dis2 = (int) abs(2*lb) + x; } else { dis1 = 2*rb + (int) abs(x); dis2 = (int) abs(x); }
if (flag2) cout << "0 0" << endl; else cout << dis1 << " " << dis2 << endl; }
system("PAUSE"); return 0; } --------------------------- I can't understand WHY WA#4 Please, help!!! It's too hard code. The real solution is much easier/ My Code perfect AC with Visual Studio 2013, G++ 4.9, G++ 4.9 C++11. But Clang 3.5 gives output limit exceeded, or access violation.... Submit codes 7217044 7217043 Some bugs in the validator were fixed. The problem was rejudged. 299 WA submits turned to AC and 84 AC submits turned to WA. If you will find new bugs, please, write to timus_support (at) acm.timus.ru. Edited by author 09.09.2010 10:57 To those who have WA at 2 after rejudge: The ending point MUST have positive (STRICTLY) coordinates. Try this testcase: 1 1 1 2 2 4 2 3 to see if your answer satisfies the condition. Thx a LOOOOT of @198808xc. I got AC . if c0 less than all of other delay times: x = 0.003 ; y = sqrt(L*L - x*x)
using namespace std; int main() { int n, d[13]; scanf("%d", &n); d[0] = 5; d[1] = 21; d[2] = 12; d[3] = 2; d[4] = 1; d[5] = 4; d[6] = 6; d[7] = 1; d[8] = 4; d[9] = 4; d[10] = 1; d[11] = 0; d[12] = 1; d[13] = 1; printf("%d", d[n]); return 0; } #include <iostream> #include <cmath> #include <cstdlib> #include <cstdio> #include <algorithm> #include <queue> #define f first #define s second #define ll long long #define ld long double #define ull unsigned long long #define pb push_back #define ppb pop_back #define mp make_pair #define sz(x) (int) x.size() #define all(x) x.begin(), x.end() #define bit(x) __builtin_popcountll(x) #define sqr(x) ((x) * 1LL * (x)) #define nl '\n' #define ioi exit(0); #define NeedForSpeed ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); #define _7day "IOI2017" using namespace std; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef pair <ld, ld> pdd; typedef pair <ll, ull> hack; const int N = 1e5 + 7, MxN = 1e6 + 7, mod = 1e9 + 7, inf = 1e9 + 7; const long long linf = (ll)1e18 + 7; const long double eps = 1e-15, pi = 3.141592; const int dx[] = {-1, 0, 1, 0, 1, -1, -1, 1}, dy[] = {0, 1, 0, -1, 1, -1, 1, -1}; int n, x; priority_queue <unsigned int> q; int main(){ #ifndef _7day freopen (_7day".in", "r", stdin); freopen (_7day".out", "w", stdout); #endif cin >> n; for (int i = 1; i <= n / 2 + 1; ++i) cin >> x, q.push(x); for (int i = n / 2 + 2; i <= n; ++i){ cin >> x; if (x < q.top()) q.pop(), q.push(x); } if (n % 2) printf ("%d.0", q.top()); else{ unsigned int top1 = q.top(); q.pop(); if ((top1 + q.top()) % 2 == 0) cout << top1 / 2 + q.top() / 2 << ".0"; else cout << top1 / 2 + q.top() / 2 << ".5"; } ioi } Edited by author 01.12.2016 20:51 Edited by author 01.12.2016 20:51 Priority queue is based on vector. When vector resizes, 2 data blocks can be allocated in one time. Let it resizes at n/2 size/capacity. Next data block capacity (assuming resize factor 1.5) is 3n/4. Even second block can cause MLE. Both blocks size is 5*n/4 - MLE. You should avoid resizing. You should better set fixed vector size (approx n/2+2) and use heap functions over it. Please can you show, how it can be done. I can't do it Edited by author 03.12.2016 14:16 I tried to do like this but whatever it's got MLE 7 vector <unsigned int> vec; vec.reserve(n / 2 + 2); priority_queue <unsigned int> q (less<unsigned int>(), vec); Google std::make_heap / std::push_heap / std::pop_heap Don't use priority queue at all std::nth_element. but need a little tricky for n <= 2*10^5 --> read all numbers and use direct nth_element (or your own implementation of Kth order statistics). for n > 2*10^5 --> read only 2*10^5 numbers and use nth_element for n - 2*10^5, and remove first n - 2*10^5, i.e. rewrite remain numbers to first n-2*10^5, and again use nth_element for n/2 - (n- 2*10^5) Good Luck!!! I see you got AC, but this description looks suspicious anyway. Let we need to process 9 elements [1,2,3,4,5,6,7,8,9] in any order (so expected answer is 5), and have 5 elements array. As I understand steps should be: for n > 5 --> (1)read only 5 numbers and use nth_element for n - 5, (2) remove first n - 5, i.e. rewrite remain numbers to 5, (3) again use nth_element for n/2 - (n- 5) Am I correct? Let see numbers in order [1,2,5,8,9,3,4,6,7] Read first 5, find (9-5) = 4th: [1,2,5,8,9] => 9 (or 8), rest removed. 5 removed, wont be answer, fail Could you please show your code? #include<stdio.h> int main(void){ int a, b; scanf("%d %d", &a, &b); if(a%2==0 || b%2!=0) puts("yes"); else if(a%2!=0 || b%2==0) puts("no"); return 0; } else puts("no"); is enough Who know O(H*W) or, O(H*W*5) algo ??? С 20 не проходит 15 тест!!! PS. У меня тесты проходит PSS. базовые) #include<iostream> #include<vector> using namespace std; int test(int a); vector<int> list; //vector<int> answers; int main() { list.push_back(0); list.push_back(1); int N; cin >> N; while (N != 0) { cout << test(N); // answers.push_back(test(N)); cin >> N; } //for (int i = 0; i < answers.size(); i++) // cout << answers[i] << endl; return 0; } int test(int a) { int i = 2; if (a < list.size() && a % 2 == 0) return list[a - 1]; else if (a < list.size() && a % 2 != 0) return list[a]; else if (a >= list.size()) i = list.size(); for (i; i <= a; i++) { if (i % 2 == 0) list.push_back(list[i / 2]); else list.push_back(list[i / 2] + list[i / 2 + 1]); } if (a % 2 == 0) return list[a - 1]; else return list[a]; } Edited by author 11.01.2017 16:19 Edited by author 11.01.2017 16:21 the same c++ code was accepted when I used visual studio, but gave TLE 8 with g++ 9 (or g++ 9, C11) Same happened to me. I've removed everything from the code except scanf("%d", &t); and it took 1.9 seconds just to read test #8 input using G++. Same code runs in 0.25 seconds under Visual C++ 2010. Thank you. I also scaned with scanf("%d", &t) and got ~1.5+/- sec using G++ and ~0.3 sec using VC++. Another idea to optimize is to scan with gets() and hex values. Edited by author 28.09.2016 00:02 Edited by author 28.09.2016 00:02 i try to solve it with kruskal and it gives me wa6 can anyone help me? struct edge { int len; int a; int b; }; int rank[1024]; int parent[1024]; edge e[15008]; int n,m; int get_parent(int x) { if (x != parent[x])parent[x] = get_parent(parent[x]); return parent[x]; } bool join_dsu(int x, int y){ x = get_parent(x); y = get_parent(y); if (x == y) return false; if (rank[x] < rank[y]) parent[x] = y; else if (rank[x] > rank[y]) parent[y] = x; else parent[y] = x, ++rank[x]; return true; } // read edges // sort edges by len // p[i] = i, for i = 1..n // let l_min = 0; // i = 1..m // if ( join_dsu( e[i].a, e[i].b) ){ l_min = e[i].len; } // print l_min and all edges where len <= l_min, GOOD LUCK !! type Ta=record x,y:extended; end; var a,b,c:Ta; ab,ac,bc,p,s,h,m:extended; l:extended; function max(a,b:extended):extended; begin if a-b>0 then max:=a else max:=b; end; begin readln(a.x,a.y,b.x,b.y); readln(c.x,c.y,l); ac:=sqrt(sqr(a.x-c.x)+sqr(a.y-c.y)); ab:=sqrt(sqr(a.x-b.x)+sqr(a.y-b.y)); bc:=sqrt(sqr(b.x-c.x)+sqr(b.y-c.y)); p:=(ab+ac+bc)/2; s:=sqrt(p*(p-ac)*(p-ab)*(p-bc)); if ab=0 then h:=ac else h:=2*s/ab; if h-l>0 then writeln(h-l:0:2) else writeln('0.00'); m:=max(ac,bc); if m-l>0 then writeln(m-l:0:2) else writeln('0.00'); end. Edited by author 03.08.2008 16:37 Try this test: -1 1 1 1 -4 -3 0 Correct answere is 5.00 6.40 I have: var ab,ca,cb,p,s1,s2,Streyg,cosA,cosB:real; Xa,Ya,Xb,Yb,Xc,Yc,L:integer; Begin Readln(Xa,Ya,Xb,Yb,Xc,Yc,L); ab:=sqrt(sqr(Xa-Xb)+sqr(Ya-Yb)); ca:=sqrt(sqr(Xa-Xc)+sqr(Ya-Yc)); cb:=sqrt(sqr(Xb-Xc)+sqr(Yb-Yc)); p:=(ab+ca+cb)/2; Streyg:=(sqrt(p*(p-ab)*(p-ca)*(p-cb)));
if ((ca>cb) and (L>=ca)) or ((ca<cb) and (L>=cb)) or ((Xa=Xb) and (Ya=Yb) and (L>=ca)) then begin s1:=0; s2:=s1; end else if (Xa=Xb) and (Ya=Yb) then begin s1:=ca; s2:=s1; end else begin if (Streyg=0) or (L>=ca) or (L>=cb) or (L>=2*Streyg/ab) then s1:=0 else begin cosA:=(ca*ca+ab*ab-cb*cb)/(2*ca*ab); cosB:=(ab*ab+cb*cb-ca*ca)/(2*ab*cb); if (cosA>=0) and (cosB>=0) then s1:=2*Streyg/ab-L else if ca>cb then s1:=cb-L else s1:=ca-L; end; if ca>cb then s2:=ca-L else s2:=cb-L; end;
writeln(s1:3:2); write(s2:3:2);
End. give me some test Why 5. Why not 4? Основание перпендикуляра не попадёт в отрезок. А по теореме Пифагора получаем для катетов 3 и 4 гипотенузу 5 import java.util.Scanner; public class Problem_1348 { public static void main(String[] args) { Scanner in=new Scanner(System.in); int ax,ay,bx,by,cx,cy,l; double ac,bc,ab,x,min,A,B,C,h; x=h=0; ax=in.nextInt(); ay=in.nextInt(); bx=in.nextInt(); by=in.nextInt(); cx=in.nextInt(); cy=in.nextInt(); l=in.nextInt();
ab= Math.sqrt( (bx-ax)*(bx-ax)+(by-ay)*(by-ay) ); ac =Math.sqrt( (cx-ax)*(cx-ax)+ (cy-ay)*(cy-ay) ); bc= Math.sqrt( (cx-bx)*(cx-bx) + (cy-by)*(cy-by) ); A=ac; B=bc; C=ab;
x=(A*A-B*B+C*C)/(2*C); h= Math.sqrt((A*A-x*x)); min=h;
if(A>B){ if(min-l<0)System.out.printf("%.2f",0.00); else System.out.printf("%.2f",min-l); System.out.println(); if(A-l<0)System.out.printf("%.2f",0.00);else System.out.printf("%.2f",A-l); }else{ if(min-l<0)System.out.printf("%.2f",0.00); else System.out.printf("%.2f",min-l); System.out.println(); if(A-l<0)System.out.printf("%.2f",0.00);else System.out.printf("%.2f",B-l); }
} } Edited by author 06.05.2014 16:57 Если основание высоты не попадает в отрезок AB, то такого расстояния не хватит #include <iostream> #include <string.h> int main() { char grif[1001][202],sliz[1001][202],huff[1001][202],rave[1001][202],name[202],group[20]; int n,i,gcur=0,scur=0,hcur=0,rcur=0; std:: cin >> n; while( n>=0 ) { std:: cin.getline(name,202); std:: cin.getline(group,20);
if(!strcmp(group,"Slytherin")) { strcpy(sliz[scur],name); scur++; } if(!strcmp(group,"Hufflepuff")) { strcpy(huff[hcur],name); hcur++; } if(!strcmp(group,"Gryffindor")) { strcpy(grif[gcur],name); gcur++; } if(!strcmp(group,"Ravenclaw")) { strcpy(rave[rcur],name); rcur++; }
--n; }
std::cout<<"Slytherin:\n"; for( i=0; i<scur; ++i ) std:: cout << sliz[i] << '\n'; std::cout<<'\n';
std::cout<<"Hufflepuff:\n"; for( i=0; i<hcur; ++i ) std:: cout << huff[i] << '\n'; std::cout<<'\n';
std::cout<<"Gryffindor:\n"; for( i=0; i<gcur; ++i ) std:: cout << grif[i] << '\n'; std::cout<<'\n';
std::cout<<"Ravenclaw:\n"; for( i=0; i<rcur; ++i ) std:: cout << rave[i] << '\n'; std::cout<<'\n';
return 0; } This is madness! Don't write such code =) int main() { int students; cin >> students; map< string, vector<string> > house_to_students; for (int student = 0; student < students; student++) { cin.ignore();
string student_name; getline(cin, student_name); string house; cin >> house; house_to_students[house].push_back(student_name); } for (auto house : { "Slytherin", "Hufflepuff", "Gryffindor", "Ravenclaw" }) { cout << house << ":" << endl;
for (auto student : house_to_students[house]) cout << student << endl; cout << endl; } } It happened bcs of cin function In the input they give n and endl after n; so, somehow getline reads this endl as a string, so you can do this insted of "cin>>n" use "scanf("%d\n", &n); #include <iostream> using namespace std; int main() { int n, res = 0; cin >> n; if (n < 0) { for (int i = -2; i >= n; i--) { res = res + i; } cout << res; } else { for (int i = 1; i <= n; i++) { res = res + i; } cout << res; } return 0; } int i = -2; i >= n; i-- i = 1 Optimization trick with initial i=-2 is funny. But now you aren't processing case "n == 0" correctly. if(n == 0) --> ans = ? bro.. i don't understand... i'm from vietnam Lets read task: > sum of all integer numbers lying between 1 and N inclusive If N==0 then set of integers to sum is [0..1], sum is 1. |
|