output
stringlengths 52
181k
| instruction
stringlengths 296
182k
|
---|---|
#include<iostream>
using namespace std;
int main(){
int n,m;
while(cin>>n){
if(n==0) break;
char c[n][2],s;
for(int i=0;i<n;i++) cin >> c[i][0] >> c[i][1];
cin >> m;
for(int i=0;i<m;i++){
cin >> s;
for(int j=0;j<n;j++){
if(s==c[j][0]){
s = c[j][1];
break;
}
}
cout << s;
}
cout << endl;
}
return 0;
}
| ### Prompt
Generate a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int n,m;
while(cin>>n){
if(n==0) break;
char c[n][2],s;
for(int i=0;i<n;i++) cin >> c[i][0] >> c[i][1];
cin >> m;
for(int i=0;i<m;i++){
cin >> s;
for(int j=0;j<n;j++){
if(s==c[j][0]){
s = c[j][1];
break;
}
}
cout << s;
}
cout << endl;
}
return 0;
}
``` |
#include<iostream>
using namespace std;
int main(){
char ch[8000];
int n,m;
char l,r;
while(1){
cin>>n;
if(n==0) break;
for(int i=0;i<3000;i++){
ch[i]='@';
}
for(int i=0;i<n;i++){
cin>>l>>r;
ch[l]=r;
}
cin>>m;
for(int i=0;i<m;i++){
cin>>l;
if(ch[l]=='@') cout<<l;
else cout<<ch[l];
}
cout<<endl;
}
return 0;
} | ### Prompt
Your task is to create a cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
char ch[8000];
int n,m;
char l,r;
while(1){
cin>>n;
if(n==0) break;
for(int i=0;i<3000;i++){
ch[i]='@';
}
for(int i=0;i<n;i++){
cin>>l>>r;
ch[l]=r;
}
cin>>m;
for(int i=0;i<m;i++){
cin>>l;
if(ch[l]=='@') cout<<l;
else cout<<ch[l];
}
cout<<endl;
}
return 0;
}
``` |
#include <stdio.h>
int main(void)
{
unsigned char table[256];
char c[2];
int n, m;
while (1){
for (int i = 0; i < 256; i++){
table[i] = i;
}
scanf("%d", &n);
if (n == 0){
break;
}
for (int i = 0; i < n; i++){
char c1[2], c2[2];
scanf("%s%s", c1, c2);
table[c1[0]] = c2[0];
}
scanf("%d", &m);
for (int i = 0; i < m; i++){
scanf("%s", c);
printf("%c", table[c[0]]);
}
puts("");
}
} | ### Prompt
Please provide a CPP coded solution to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <stdio.h>
int main(void)
{
unsigned char table[256];
char c[2];
int n, m;
while (1){
for (int i = 0; i < 256; i++){
table[i] = i;
}
scanf("%d", &n);
if (n == 0){
break;
}
for (int i = 0; i < n; i++){
char c1[2], c2[2];
scanf("%s%s", c1, c2);
table[c1[0]] = c2[0];
}
scanf("%d", &m);
for (int i = 0; i < m; i++){
scanf("%s", c);
printf("%c", table[c[0]]);
}
puts("");
}
}
``` |
#include<iostream>
#include<map>
using namespace std;
int main(){
map<char,char> table;
int n;
char s,t;
while(cin>>n&&n){
table.clear();
while(n--){
cin>>s>>t;
table[s] = t;
}
cin>>n;
while(n--){
cin>>s;
if(table.find(s)!=table.end())cout<<table[s];
else cout<<s;
}
cout<<endl;
}
return 0;
} | ### Prompt
Develop a solution in Cpp to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
#include<map>
using namespace std;
int main(){
map<char,char> table;
int n;
char s,t;
while(cin>>n&&n){
table.clear();
while(n--){
cin>>s>>t;
table[s] = t;
}
cin>>n;
while(n--){
cin>>s;
if(table.find(s)!=table.end())cout<<table[s];
else cout<<s;
}
cout<<endl;
}
return 0;
}
``` |
#include <iostream>
#include <map>
using namespace std;
int main(void){
int n;
char c1,c2;
map <char,char> m;
while( cin >> n , n ){
m.clear();
for( int i = 0 ; i < n ; i++ ){
cin >> c1 >> c2;
m[c1] = c2;
}
cin >> n;
while(n--){
cin >> c1;
if( m[c1] ) cout << m[c1];
else cout << c1;
}
cout << endl;
}
return 0;
} | ### Prompt
Develop a solution in cpp to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <map>
using namespace std;
int main(void){
int n;
char c1,c2;
map <char,char> m;
while( cin >> n , n ){
m.clear();
for( int i = 0 ; i < n ; i++ ){
cin >> c1 >> c2;
m[c1] = c2;
}
cin >> n;
while(n--){
cin >> c1;
if( m[c1] ) cout << m[c1];
else cout << c1;
}
cout << endl;
}
return 0;
}
``` |
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main(){
int n,m;
while( cin >> n , n ){
map<char,char> f;
for(int i=0 ; i<n ; ++i ){
char c , c_;
cin >> c >> c_ ;
f[c] = c_;
}
cin >> m;
string s;
for(int i=0 ; i<m ; ++i ){
char c;
cin >> c;
if( f.count( c ) )
s.push_back( f[c] );
else
s.push_back( c );
}
cout << s << endl;
}
} | ### Prompt
Generate a cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main(){
int n,m;
while( cin >> n , n ){
map<char,char> f;
for(int i=0 ; i<n ; ++i ){
char c , c_;
cin >> c >> c_ ;
f[c] = c_;
}
cin >> m;
string s;
for(int i=0 ; i<m ; ++i ){
char c;
cin >> c;
if( f.count( c ) )
s.push_back( f[c] );
else
s.push_back( c );
}
cout << s << endl;
}
}
``` |
#include <iostream>
using namespace std;
int main(void){
char a[100000],b[100000],c;
int m,n,f;
while(1){
cin>>n;
if(!n)
break;
for(int i=0;i<n;i++)
cin>>a[i]>>b[i];
cin>>m;
for(int j=0;j<m;j++){
f=1;
cin>>c;
for(int k=0;k<n;k++){
if(c==a[k]){
f=0;
cout<<b[k];
break;
}
}
if(f)
cout<<c;
}
cout<<endl;
}
return 0;
} | ### Prompt
Generate a cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
using namespace std;
int main(void){
char a[100000],b[100000],c;
int m,n,f;
while(1){
cin>>n;
if(!n)
break;
for(int i=0;i<n;i++)
cin>>a[i]>>b[i];
cin>>m;
for(int j=0;j<m;j++){
f=1;
cin>>c;
for(int k=0;k<n;k++){
if(c==a[k]){
f=0;
cout<<b[k];
break;
}
}
if(f)
cout<<c;
}
cout<<endl;
}
return 0;
}
``` |
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
int main(){
int n;
while (cin >> n, n){
map<char, char> mp;
while (n--){
char c, d;
cin >> c >> d;
mp[c] = d;
}
int m;
cin >> m;
while (m--){
char c;
cin >> c;
if (mp.count(c)){
cout << mp[c];
}
else{
cout << c;
}
}
cout << endl;
}
return 0;
} | ### Prompt
Create a solution in Cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
int main(){
int n;
while (cin >> n, n){
map<char, char> mp;
while (n--){
char c, d;
cin >> c >> d;
mp[c] = d;
}
int m;
cin >> m;
while (m--){
char c;
cin >> c;
if (mp.count(c)){
cout << mp[c];
}
else{
cout << c;
}
}
cout << endl;
}
return 0;
}
``` |
#include<iostream>
using namespace std;
int main(){
int n,m;
while(cin>>n,n){
char a,b,l[62] = {0};
while(n--)
cin >> a >> b,l[a > 96?a - 97:a > 64?a - 39:a > 47?a + 4:0] = b;
cin >> m;
string s = "";
while(m--){
cin >> a;b = l[a > 96?a - 97:a > 64?a - 39:a > 47?a + 4:0];if(b==0)b = a;s+=b;}
cout << s << endl;
}
} | ### Prompt
Develop a solution in Cpp to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int n,m;
while(cin>>n,n){
char a,b,l[62] = {0};
while(n--)
cin >> a >> b,l[a > 96?a - 97:a > 64?a - 39:a > 47?a + 4:0] = b;
cin >> m;
string s = "";
while(m--){
cin >> a;b = l[a > 96?a - 97:a > 64?a - 39:a > 47?a + 4:0];if(b==0)b = a;s+=b;}
cout << s << endl;
}
}
``` |
#include <iostream>
using namespace std;
int main(){long n;while(cin>>n,n){char d,s,m[256]={0};for(;n--;m[(int)s]=d)cin>>s>>d;for(cin>>n;n--;cout<<(m[(int)s]?m[(int)s]:s))cin>>s;cout<<endl;}} | ### Prompt
Your task is to create a cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
using namespace std;
int main(){long n;while(cin>>n,n){char d,s,m[256]={0};for(;n--;m[(int)s]=d)cin>>s>>d;for(cin>>n;n--;cout<<(m[(int)s]?m[(int)s]:s))cin>>s;cout<<endl;}}
``` |
#include<iostream>
using namespace std;
int main(){
char a[100000][2];
int n,m;
char in;
while(cin>>n,n){
for(int i=0;i<n;i++){
cin>>a[i][0]>>a[i][1];
}
cin>>m;
for(int i=0;i<m;i++){
cin>>in;
bool flg=true;
for(int j=0;j<n;j++){
if(a[j][0]==in){cout<<a[j][1];flg=false;break;}
}
if(flg)cout<<in;
}
cout<<endl;
}
} | ### Prompt
In CPP, your task is to solve the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
char a[100000][2];
int n,m;
char in;
while(cin>>n,n){
for(int i=0;i<n;i++){
cin>>a[i][0]>>a[i][1];
}
cin>>m;
for(int i=0;i<m;i++){
cin>>in;
bool flg=true;
for(int j=0;j<n;j++){
if(a[j][0]==in){cout<<a[j][1];flg=false;break;}
}
if(flg)cout<<in;
}
cout<<endl;
}
}
``` |
#include<iostream>
#include<map>
using namespace std;
int main()
{
int n,m;
char c1,c2;
map<char,char>convert;
while(cin>>n,n){
convert.clear();
while(n-->0){
cin>>c1>>c2;
convert[c1]=c2;
}
cin>>m;
while(m-->0){
cin>>c1;
if(convert.find(c1)!=convert.end())printf("%c",convert[c1]);
else printf("%c",c1);
}
puts("");
}
} | ### Prompt
Create a solution in cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
#include<map>
using namespace std;
int main()
{
int n,m;
char c1,c2;
map<char,char>convert;
while(cin>>n,n){
convert.clear();
while(n-->0){
cin>>c1>>c2;
convert[c1]=c2;
}
cin>>m;
while(m-->0){
cin>>c1;
if(convert.find(c1)!=convert.end())printf("%c",convert[c1]);
else printf("%c",c1);
}
puts("");
}
}
``` |
#include<iostream>
#include<string>
using namespace std;
int main(){
int n,m;
char a[100],b[100],c[100001];
while(true){
cin>>n;
if(n==0)
break;
for(int i=0;i<n;i++)
cin>>a[i]>>b[i];
cin>>m;
for(int i=0;i<m;i++){
cin>>c[i];
int j=0;
while(true){
if(a[j]==c[i]){
c[i]=b[j];
break;
}
j++;
if(j==n)
break;
}
}
for(int i=0;i<m;i++)
cout<<c[i];
cout<<endl;
}
return 0;
}
| ### Prompt
Create a solution in cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
#include<string>
using namespace std;
int main(){
int n,m;
char a[100],b[100],c[100001];
while(true){
cin>>n;
if(n==0)
break;
for(int i=0;i<n;i++)
cin>>a[i]>>b[i];
cin>>m;
for(int i=0;i<m;i++){
cin>>c[i];
int j=0;
while(true){
if(a[j]==c[i]){
c[i]=b[j];
break;
}
j++;
if(j==n)
break;
}
}
for(int i=0;i<m;i++)
cout<<c[i];
cout<<endl;
}
return 0;
}
``` |
#include <iostream>
#include <vector>
using namespace std;
int main(void){
while (1) {
int n; cin >> n;
if (!n) break;
vector<char> v1, v2;
for (int i = 0; i < n; i++) {
char c;
cin >> c; v1.push_back(c);
cin >> c; v2.push_back(c);
}
int m; cin >> m;
for (int i = 0; i < m; i++) {
char b; cin >> b;
for (int j = 0; j < n; j++) {
if (b == v1[j]) {
b = v2[j];
break;
}
}
cout << b;
}
cout << endl;
}
}
| ### Prompt
Create a solution in cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main(void){
while (1) {
int n; cin >> n;
if (!n) break;
vector<char> v1, v2;
for (int i = 0; i < n; i++) {
char c;
cin >> c; v1.push_back(c);
cin >> c; v2.push_back(c);
}
int m; cin >> m;
for (int i = 0; i < m; i++) {
char b; cin >> b;
for (int j = 0; j < n; j++) {
if (b == v1[j]) {
b = v2[j];
break;
}
}
cout << b;
}
cout << endl;
}
}
``` |
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
int c;
string d;
int m;
int e;
int f;
while(cin >> n){
if(n!=0){
string a[n];
string b[n];
c=0;
while(c<n){
cin >>a[c];
cin >>b[c];
c=c+1;}
cin >> m;
c=0;
while(c<m){
cin >>d;
e=0;
f=0;
while(e<n){
if(d==a[e]){cout<<b[e]; f=1;}
e=e+1;
}
if(f==0){cout <<d;}
c=c+1;}
cout << endl;
}
}
} | ### Prompt
Develop a solution in Cpp to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
int c;
string d;
int m;
int e;
int f;
while(cin >> n){
if(n!=0){
string a[n];
string b[n];
c=0;
while(c<n){
cin >>a[c];
cin >>b[c];
c=c+1;}
cin >> m;
c=0;
while(c<m){
cin >>d;
e=0;
f=0;
while(e<n){
if(d==a[e]){cout<<b[e]; f=1;}
e=e+1;
}
if(f==0){cout <<d;}
c=c+1;}
cout << endl;
}
}
}
``` |
#include<iostream>
using namespace std;
int main(){
int n,m;
while(1){
cin>>n;
char a[n],b[n],cha;
if(n==0)
break;
for(int i=0;i<n;i++){
cin>>a[i]>>b[i];
}
cin>>m;
for(int i=0;i<m;i++){
cin>>cha;
for(int j=0;j<n;j++){
if(cha==a[j]){
cout<<b[j];
break;
}else if(j+1==n){
cout<<cha;
}
}
}
cout<<endl;
}
} | ### Prompt
Construct a CPP code solution to the problem outlined:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int n,m;
while(1){
cin>>n;
char a[n],b[n],cha;
if(n==0)
break;
for(int i=0;i<n;i++){
cin>>a[i]>>b[i];
}
cin>>m;
for(int i=0;i<m;i++){
cin>>cha;
for(int j=0;j<n;j++){
if(cha==a[j]){
cout<<b[j];
break;
}else if(j+1==n){
cout<<cha;
}
}
}
cout<<endl;
}
}
``` |
#include <cstdio>
#include <cstring>
char c[128];
int main(void)
{
while(1){
int n;
scanf("%d",&n);
if(!n) break;
memset(c,0,sizeof(c));
for(int i=0;i<n;i++){
char a,b;
scanf(" %c %c",&a,&b);
c[a] = b;
}
int m;
scanf("%d",&m);
for(int i=0;i<m;i++){
char a;
scanf(" %c",&a);
if(c[a]){
printf("%c",c[a]);
} else {
printf("%c",a);
}
}
puts("");
}
} | ### Prompt
Please create a solution in cpp to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <cstdio>
#include <cstring>
char c[128];
int main(void)
{
while(1){
int n;
scanf("%d",&n);
if(!n) break;
memset(c,0,sizeof(c));
for(int i=0;i<n;i++){
char a,b;
scanf(" %c %c",&a,&b);
c[a] = b;
}
int m;
scanf("%d",&m);
for(int i=0;i<m;i++){
char a;
scanf(" %c",&a);
if(c[a]){
printf("%c",c[a]);
} else {
printf("%c",a);
}
}
puts("");
}
}
``` |
#include <stdio.h>
int main() {
char trans[256];
char c, c2, str[10];
long n, m, i;
while (scanf("%ld", &n), n) {
for (i = 0; i < 256; ++i)
trans[i] = i;
for (i = 0; i < n; ++i) {
scanf("%s", str); c = str[0];
scanf("%s", str); c2 = str[0];
trans[c] = c2;
}
scanf("%ld", &m);
for (i = 0; i < m; ++i) {
scanf("%s", str); c = str[0];
printf("%c", trans[c]);
}
puts("");
}
return 0;
} | ### Prompt
Your challenge is to write a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <stdio.h>
int main() {
char trans[256];
char c, c2, str[10];
long n, m, i;
while (scanf("%ld", &n), n) {
for (i = 0; i < 256; ++i)
trans[i] = i;
for (i = 0; i < n; ++i) {
scanf("%s", str); c = str[0];
scanf("%s", str); c2 = str[0];
trans[c] = c2;
}
scanf("%ld", &m);
for (i = 0; i < m; ++i) {
scanf("%s", str); c = str[0];
printf("%c", trans[c]);
}
puts("");
}
return 0;
}
``` |
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin >> n, n){
char a,b;
char d[1000];
for(int i = 0; i < 1000; i++)
d[i] = -1;
while(n > 0){
n--;
cin >> a >> b;
d[a] = b;
}
cin >> n;
char *s = new char[n+1];
for(int i = 0; i < n; i++){
cin >> a;
if(d[a] != -1)
s[i] = d[a];
else
s[i] = a;
}
s[n] = '\0';
cout << s << endl;
}
return 0;
} | ### Prompt
Generate a cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin >> n, n){
char a,b;
char d[1000];
for(int i = 0; i < 1000; i++)
d[i] = -1;
while(n > 0){
n--;
cin >> a >> b;
d[a] = b;
}
cin >> n;
char *s = new char[n+1];
for(int i = 0; i < n; i++){
cin >> a;
if(d[a] != -1)
s[i] = d[a];
else
s[i] = a;
}
s[n] = '\0';
cout << s << endl;
}
return 0;
}
``` |
#include<iostream>
#include<map>
using namespace std;
int main(void){
int n,m;
while(cin >> n, n != 0){
char c, d;
map<char, char> tb;
for(int i = 0; i < n; i++){
cin >> c >> d;
tb[c] = d;
}
cin >> m;
for(int i = 0; i < m; i++){
cin >> c;
if(tb.find(c) != tb.end())
cout << tb[c];
else
cout << c;
}
cout << endl;
}
return 0;
} | ### Prompt
Your challenge is to write a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
#include<map>
using namespace std;
int main(void){
int n,m;
while(cin >> n, n != 0){
char c, d;
map<char, char> tb;
for(int i = 0; i < n; i++){
cin >> c >> d;
tb[c] = d;
}
cin >> m;
for(int i = 0; i < m; i++){
cin >> c;
if(tb.find(c) != tb.end())
cout << tb[c];
else
cout << c;
}
cout << endl;
}
return 0;
}
``` |
#include <iostream>
#include <string>
using namespace std;
int main() {
while(1){
int a;
cin >> a;
if(a == 0){break;}
char *b = new char [a];
char *c = new char [a];
for(int i = 0;i < a;i++){
cin >> b[i] >> c[i];
}
int m;
cin >> m;
for(int i = 1;i <= m;i++){
char p;
cin >> p;
int ii = 0;
while(ii < a){
if(p == b[ii]){
p = c[ii];
break;
}
ii++;
}
if(i == m){cout << p << endl;}
else{cout << p;}
}
}
return 0;
} | ### Prompt
Please provide a CPP coded solution to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
while(1){
int a;
cin >> a;
if(a == 0){break;}
char *b = new char [a];
char *c = new char [a];
for(int i = 0;i < a;i++){
cin >> b[i] >> c[i];
}
int m;
cin >> m;
for(int i = 1;i <= m;i++){
char p;
cin >> p;
int ii = 0;
while(ii < a){
if(p == b[ii]){
p = c[ii];
break;
}
ii++;
}
if(i == m){cout << p << endl;}
else{cout << p;}
}
}
return 0;
}
``` |
#include<iostream>
using namespace std;
char map[256];
int main(){
while(true){
for(int i = 0;i < 256;i++){
map[i] = i;
}
int n;
cin >> n;
if(n==0)break;
for(int i = 0; i < n;i ++){
char c,d;
cin >> c >> d;
map[c] = d;
}
cin >> n;
for(int i = 0;i < n;i++){
char c;
cin >> c;
cout << map[c];
}
cout << endl;
}
} | ### Prompt
Your challenge is to write a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
char map[256];
int main(){
while(true){
for(int i = 0;i < 256;i++){
map[i] = i;
}
int n;
cin >> n;
if(n==0)break;
for(int i = 0; i < n;i ++){
char c,d;
cin >> c >> d;
map[c] = d;
}
cin >> n;
for(int i = 0;i < n;i++){
char c;
cin >> c;
cout << map[c];
}
cout << endl;
}
}
``` |
#include <cstdio>
int main(){
int n, m;
static int dict[256];
char k, v, x;
while (scanf("%d\n", &n)){
if (!n) return 0;
for (int i = 0; i<256; i++) dict[i] = i;
for (int i = 0; i<n; i++){
scanf("%c %c\n", &k, &v);
dict[(int)k] = (int)v;
}
scanf("%d\n", &m);
for (int i = 0; i<m; i++){
scanf("%c\n", &x);
printf("%c", dict[(int)x]);
}
printf("\n");
}
} | ### Prompt
Please formulate a CPP solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <cstdio>
int main(){
int n, m;
static int dict[256];
char k, v, x;
while (scanf("%d\n", &n)){
if (!n) return 0;
for (int i = 0; i<256; i++) dict[i] = i;
for (int i = 0; i<n; i++){
scanf("%c %c\n", &k, &v);
dict[(int)k] = (int)v;
}
scanf("%d\n", &m);
for (int i = 0; i<m; i++){
scanf("%c\n", &x);
printf("%c", dict[(int)x]);
}
printf("\n");
}
}
``` |
#include <iostream>
#include <map>
using namespace std;
int main ( void )
{
int n;
while ( cin >> n, n )
{
map<char, char> t;
for (int i = 0; i < n; ++i)
{
char a, b;
cin >> a >> b;
t[a] = b;
}
int m;
cin >> m;
for (int i = 0; i < m; ++i)
{
char c;
cin >> c;
if ( t.count(c) )
cout << t[c];
else
cout << c;
}
cout << endl;
}
return 0;
} | ### Prompt
Please create a solution in Cpp to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <map>
using namespace std;
int main ( void )
{
int n;
while ( cin >> n, n )
{
map<char, char> t;
for (int i = 0; i < n; ++i)
{
char a, b;
cin >> a >> b;
t[a] = b;
}
int m;
cin >> m;
for (int i = 0; i < m; ++i)
{
char c;
cin >> c;
if ( t.count(c) )
cout << t[c];
else
cout << c;
}
cout << endl;
}
return 0;
}
``` |
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
while( cin >> n, n ) {
map<char,char> data;
for(int i=0; i<n; i++) {
char c1, c2;
cin >> c1 >> c2;
data[c1] = c2;
}
int m;
char c;
string s = "";
cin >> m;
for(int i=0; i<m; i++) {
cin >> c;
if (data.find(c) != data.end()) {
s += data[c];
}
else {
s += c;
}
}
cout << s << endl;
}
} | ### Prompt
Construct a Cpp code solution to the problem outlined:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
while( cin >> n, n ) {
map<char,char> data;
for(int i=0; i<n; i++) {
char c1, c2;
cin >> c1 >> c2;
data[c1] = c2;
}
int m;
char c;
string s = "";
cin >> m;
for(int i=0; i<m; i++) {
cin >> c;
if (data.find(c) != data.end()) {
s += data[c];
}
else {
s += c;
}
}
cout << s << endl;
}
}
``` |
#include<iostream>
class table{
char tab[128];
public:
table(){for(unsigned char i=0;i<128;++i)tab[i]=i;}
char& operator[](char p){return tab[p];}
const char& operator[](char p)const{return tab[p];}
};
int main(){
int n;
while(1){
std::cin>>n;
if(!n)return 0;
table tab;
while(n--){char a,b;std::cin>>a>>b;tab[a]=b;}
std::cin>>n;
while(n--){char a;std::cin>>a;std::cout<<tab[a];}
std::cout<<std::endl;
}
} | ### Prompt
Your task is to create a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
class table{
char tab[128];
public:
table(){for(unsigned char i=0;i<128;++i)tab[i]=i;}
char& operator[](char p){return tab[p];}
const char& operator[](char p)const{return tab[p];}
};
int main(){
int n;
while(1){
std::cin>>n;
if(!n)return 0;
table tab;
while(n--){char a,b;std::cin>>a>>b;tab[a]=b;}
std::cin>>n;
while(n--){char a;std::cin>>a;std::cout<<tab[a];}
std::cout<<std::endl;
}
}
``` |
#include <stdio.h>
int main(void) {
int n,m;
char trans[100][2];
char c;
while (scanf("%d", &n), n) {
for (int i = 0; i < n; i++) {
scanf(" %c %c", &trans[i][0], &trans[i][1]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf(" %c", &c);
for (int j = 0; j < n; j++) {
if (trans[j][0] == c) {
c = trans[j][1];
break;
}
}
printf("%c", c);
}
printf("\n");
}
return 0;
} | ### Prompt
Create a solution in cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <stdio.h>
int main(void) {
int n,m;
char trans[100][2];
char c;
while (scanf("%d", &n), n) {
for (int i = 0; i < n; i++) {
scanf(" %c %c", &trans[i][0], &trans[i][1]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf(" %c", &c);
for (int j = 0; j < n; j++) {
if (trans[j][0] == c) {
c = trans[j][1];
break;
}
}
printf("%c", c);
}
printf("\n");
}
return 0;
}
``` |
#include <iostream>
using namespace std;
int main(){
int n,m,i=0,j=0,k=0;
char rule[50][2],data[100000];
while(j<5){
cin>>n;
if(n==0){break;}
for(i=0;i<n;i++){
cin>>rule[i][0];
cin>>rule[i][1];
}
cin>>m;
for(i=0;i<m;i++){
cin>>data[i];
for(k=0;k<n;k++){
if(data[i]==rule[k][0]){
data[i]=rule[k][1];
break;
}
}
}
for(i=0;i<m;i++){
cout<<data[i];
}
cout<<endl;
j++;
}
return 0;
}
| ### Prompt
In Cpp, your task is to solve the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
using namespace std;
int main(){
int n,m,i=0,j=0,k=0;
char rule[50][2],data[100000];
while(j<5){
cin>>n;
if(n==0){break;}
for(i=0;i<n;i++){
cin>>rule[i][0];
cin>>rule[i][1];
}
cin>>m;
for(i=0;i<m;i++){
cin>>data[i];
for(k=0;k<n;k++){
if(data[i]==rule[k][0]){
data[i]=rule[k][1];
break;
}
}
}
for(i=0;i<m;i++){
cout<<data[i];
}
cout<<endl;
j++;
}
return 0;
}
``` |
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main(){
int n;
char a,b;
map<char,char> m;
string s;
while(cin>>n,n){
m.clear();
while(n--){
cin>>a>>b;
m[a]=b;
}
cin>>n;
s="";
while(n--){
cin>>a;
if(m.find(a)==m.end()) s+=a;
else s+=m[a];
}
cout<<s<<endl;
}
return 0;
} | ### Prompt
Construct a cpp code solution to the problem outlined:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main(){
int n;
char a,b;
map<char,char> m;
string s;
while(cin>>n,n){
m.clear();
while(n--){
cin>>a>>b;
m[a]=b;
}
cin>>n;
s="";
while(n--){
cin>>a;
if(m.find(a)==m.end()) s+=a;
else s+=m[a];
}
cout<<s<<endl;
}
return 0;
}
``` |
#include <iostream>
#include <vector>
using namespace std;
int main(){
while(1){
int n;
cin >> n;
if(n==0) break;
vector<char> conv(128);
for(int i=0; i<128; i++) conv[i]=i;
for(int i=0; i<n; i++){
char a,b;
cin >> a >> b;
conv[a] = b;
}
int m;
cin >> m;
for(int i=0; i<m; i++){
char a;
cin >> a;
cout << conv[a];
}
cout << endl;
}
return 0;
} | ### Prompt
Develop a solution in cpp to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main(){
while(1){
int n;
cin >> n;
if(n==0) break;
vector<char> conv(128);
for(int i=0; i<128; i++) conv[i]=i;
for(int i=0; i<n; i++){
char a,b;
cin >> a >> b;
conv[a] = b;
}
int m;
cin >> m;
for(int i=0; i<m; i++){
char a;
cin >> a;
cout << conv[a];
}
cout << endl;
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
int main(){
int N,M;
char graph[128];
while(cin >> N,N){
for(int i = 0;i < 128;i++)graph[i] = i;
char a,b;
for(int i = 0;i < N;i++){
cin >> a >> b;
graph[a] = b;
}
cin >> M;
for(int i = 0;i < M;i++){
cin >> a;
cout << graph[a];
}
cout << endl;
}
return 0;
} | ### Prompt
Your challenge is to write a CPP solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int N,M;
char graph[128];
while(cin >> N,N){
for(int i = 0;i < 128;i++)graph[i] = i;
char a,b;
for(int i = 0;i < N;i++){
cin >> a >> b;
graph[a] = b;
}
cin >> M;
for(int i = 0;i < M;i++){
cin >> a;
cout << graph[a];
}
cout << endl;
}
return 0;
}
``` |
#include <map>
#include <iostream>
using namespace std;
int main()
{
int N, M;
char A, B, C;
while (true)
{
cin >> N;
if (N == 0) { break; }
map<char, char> converse;
for (char i = '0'; i <= 'z'; i++)
{
converse[i] = i;
}
for (int i = 0; i < N; i++)
{
cin >> A >> B;
converse[A] = B;
}
cin >> M;
for (int i = 0; i < M; i++)
{
cin >> C;
cout << converse[C];
}
cout << endl;
}
return 0;
} | ### Prompt
Please create a solution in cpp to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <map>
#include <iostream>
using namespace std;
int main()
{
int N, M;
char A, B, C;
while (true)
{
cin >> N;
if (N == 0) { break; }
map<char, char> converse;
for (char i = '0'; i <= 'z'; i++)
{
converse[i] = i;
}
for (int i = 0; i < N; i++)
{
cin >> A >> B;
converse[A] = B;
}
cin >> M;
for (int i = 0; i < M; i++)
{
cin >> C;
cout << converse[C];
}
cout << endl;
}
return 0;
}
``` |
#include<cstdio>
#include<map>
using namespace std;
int main(){
int n,m;
char a,b;
while(scanf(" %d ",&n),n){
map<char,char> t;
for(int i=0;i<n;i++){
scanf(" %c %c ",&a,&b);
t[a] = b;
}
scanf(" %d ",&m);
for(int i=0;i<m;i++){
scanf(" %c ",&a);
if(t.find(a)!=t.end())putchar(t[a]);
else putchar(a);
}
putchar('\n');
}
}
| ### Prompt
Your task is to create a CPP solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<cstdio>
#include<map>
using namespace std;
int main(){
int n,m;
char a,b;
while(scanf(" %d ",&n),n){
map<char,char> t;
for(int i=0;i<n;i++){
scanf(" %c %c ",&a,&b);
t[a] = b;
}
scanf(" %d ",&m);
for(int i=0;i<m;i++){
scanf(" %c ",&a);
if(t.find(a)!=t.end())putchar(t[a]);
else putchar(a);
}
putchar('\n');
}
}
``` |
#include<stdio.h>
int main(void)
{
int n,m;
char a[1000],b[1000],c;
int i,j;
scanf("%d",&n);
while(n!=0){
for(i=0;i<n;i++){
scanf(" %c %c",&a[i],&b[i]);
}
scanf("%d",&m);
for(i=0;i<m;i++){
scanf(" %c",&c);
for(j=0;j<n;j++){
if(c==a[j]){
c=b[j];
break;
}
}
printf("%c",c);
}
printf("\n");
scanf("%d",&n);
}
return 0;
} | ### Prompt
Generate a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<stdio.h>
int main(void)
{
int n,m;
char a[1000],b[1000],c;
int i,j;
scanf("%d",&n);
while(n!=0){
for(i=0;i<n;i++){
scanf(" %c %c",&a[i],&b[i]);
}
scanf("%d",&m);
for(i=0;i<m;i++){
scanf(" %c",&c);
for(j=0;j<n;j++){
if(c==a[j]){
c=b[j];
break;
}
}
printf("%c",c);
}
printf("\n");
scanf("%d",&n);
}
return 0;
}
``` |
#include<iostream>
using namespace std;
int main(){
int n,r;
char a[1000],b[1000],x,y;
while(cin>>n,n){
for(int i=0;i<n;i++){
cin>>x>>y;
a[i]=x;
b[i]=y;
}
cin>>r;
for(int i=0;i<r;i++){
cin>>x;
int j;
for(j=0;j<n;j++)
if(a[j]==x){
cout<<b[j];
break;
}
if(j==n)
cout<<x;
}
cout<<endl;
}
return 0;
} | ### Prompt
Please create a solution in CPP to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
int main(){
int n,r;
char a[1000],b[1000],x,y;
while(cin>>n,n){
for(int i=0;i<n;i++){
cin>>x>>y;
a[i]=x;
b[i]=y;
}
cin>>r;
for(int i=0;i<r;i++){
cin>>x;
int j;
for(j=0;j<n;j++)
if(a[j]==x){
cout<<b[j];
break;
}
if(j==n)
cout<<x;
}
cout<<endl;
}
return 0;
}
``` |
#include <stdio.h>
int main(){
int n,i,j,m,f;
char a[256],b[256],x;
while(1){
scanf("%d ",&n);
if(n==0){
break;
}
for(i=0;i<n;i++){
scanf("%c %c ",&a[i],&b[i]);
}
scanf("%d ",&m);
for(i=0;i<m;i++){
scanf("%s",&x);
f=0;
for(j=0;j<n;j++){
if(x==a[j]){
printf("%c",b[j]);
f=1;
break;
}
}
if(f==0){
printf("%c",x);
}
}
printf("\n");
}
return 0;
} | ### Prompt
Your task is to create a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <stdio.h>
int main(){
int n,i,j,m,f;
char a[256],b[256],x;
while(1){
scanf("%d ",&n);
if(n==0){
break;
}
for(i=0;i<n;i++){
scanf("%c %c ",&a[i],&b[i]);
}
scanf("%d ",&m);
for(i=0;i<m;i++){
scanf("%s",&x);
f=0;
for(j=0;j<n;j++){
if(x==a[j]){
printf("%c",b[j]);
f=1;
break;
}
}
if(f==0){
printf("%c",x);
}
}
printf("\n");
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
int main(){
int N,M;
char graph[128];
while(cin >> N,N){
for(int i = 0;i < 128;i++)graph[i] = i;
char a,b;
for(int i = 0;i < N;i++){
scanf(" %c %c",&a,&b);
graph[a] = b;
}
cin >> M;
for(int i = 0;i < M;i++){
scanf(" %c",&a);
cout << graph[a];
}
cout << endl;
}
return 0;
} | ### Prompt
Please provide a Cpp coded solution to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
int N,M;
char graph[128];
while(cin >> N,N){
for(int i = 0;i < 128;i++)graph[i] = i;
char a,b;
for(int i = 0;i < N;i++){
scanf(" %c %c",&a,&b);
graph[a] = b;
}
cin >> M;
for(int i = 0;i < M;i++){
scanf(" %c",&a);
cout << graph[a];
}
cout << endl;
}
return 0;
}
``` |
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
while(1){
int n;
scanf("%d",&n);
if(n==0)break;
char f[1002];
for(int i=0;i<1002;i++)f[i]=(char)i;
for(int i=0;i<n;i++){
char c,d;
scanf("\n%c %c",&c,&d);
f[(int)c] = d;
}
int m;
scanf("%d",&m);
for(int i=0;i<m;i++){
char c;
scanf("\n%c",&c);
printf("%c",f[(int)c]);
}
printf("\n");
}
} | ### Prompt
Please create a solution in Cpp to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
while(1){
int n;
scanf("%d",&n);
if(n==0)break;
char f[1002];
for(int i=0;i<1002;i++)f[i]=(char)i;
for(int i=0;i<n;i++){
char c,d;
scanf("\n%c %c",&c,&d);
f[(int)c] = d;
}
int m;
scanf("%d",&m);
for(int i=0;i<m;i++){
char c;
scanf("\n%c",&c);
printf("%c",f[(int)c]);
}
printf("\n");
}
}
``` |
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
int n;
while (cin >> n && n != 0){
map<string, string> m;
string s1, s2;
for (int i = 0; i < n; i++){
cin >> s1 >> s2;
m[s1] = s2;
}
cin >> n;
string line;
for (int i = 0; i < n; i++){
cin >> s1;
if (m.find(s1) != m.end()){
s1 = m[s1];
}
line += s1;
}
cout << line << endl;
}
return 0;
}
| ### Prompt
Generate a cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
int n;
while (cin >> n && n != 0){
map<string, string> m;
string s1, s2;
for (int i = 0; i < n; i++){
cin >> s1 >> s2;
m[s1] = s2;
}
cin >> n;
string line;
for (int i = 0; i < n; i++){
cin >> s1;
if (m.find(s1) != m.end()){
s1 = m[s1];
}
line += s1;
}
cout << line << endl;
}
return 0;
}
``` |
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
while (cin >> n, n)
{
map<char, char> table;
for (int i = 0; i < n; i++)
{
char a, b;
cin >> a >> b;
table[a] = b;
}
cin >> n;
for (int i = 0; i < n; i++)
{
char c;
cin >> c;
if (table.count(c)) cout << table[c];
else cout << c;
}
cout << endl;
}
return 0;
} | ### Prompt
Create a solution in CPP for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
while (cin >> n, n)
{
map<char, char> table;
for (int i = 0; i < n; i++)
{
char a, b;
cin >> a >> b;
table[a] = b;
}
cin >> n;
for (int i = 0; i < n; i++)
{
char c;
cin >> c;
if (table.count(c)) cout << table[c];
else cout << c;
}
cout << endl;
}
return 0;
}
``` |
#include "iostream"
#include "map"
#include "string"
using namespace std;
int main(void)
{
int n;
while (cin>>n,n) {
map<char, char> m;
for (int i = 0; i < n; i++) {
char l,r; cin>>l>>r;
m[l]=r;
}
string ans="";
int num; cin>>num;
while (num--) {
char t; cin>>t;
if(m.count(t)) ans+=m[t];
else ans+=t;
}
cout<<ans<<endl;
}
return 0;
} | ### Prompt
Please create a solution in Cpp to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include "iostream"
#include "map"
#include "string"
using namespace std;
int main(void)
{
int n;
while (cin>>n,n) {
map<char, char> m;
for (int i = 0; i < n; i++) {
char l,r; cin>>l>>r;
m[l]=r;
}
string ans="";
int num; cin>>num;
while (num--) {
char t; cin>>t;
if(m.count(t)) ans+=m[t];
else ans+=t;
}
cout<<ans<<endl;
}
return 0;
}
``` |
#include <iostream>
using namespace std;
int main() {
int n, m;
while(cin >> n, n) {
cin.ignore();
int conv[256] = {};
for(int i = 0; i < n; i++) {
char c, d;
cin >> c; cin.ignore();
cin >> d; cin.ignore();
conv[c] = d;
}
cin >> m; cin.ignore();
for(int i = 0; i < m; i++) {
char c;
cin >> c; cin.ignore();
if(conv[c])
cout << (char)conv[c];
else
cout << c;
}
cout << endl;
}
} | ### Prompt
Your challenge is to write a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
using namespace std;
int main() {
int n, m;
while(cin >> n, n) {
cin.ignore();
int conv[256] = {};
for(int i = 0; i < n; i++) {
char c, d;
cin >> c; cin.ignore();
cin >> d; cin.ignore();
conv[c] = d;
}
cin >> m; cin.ignore();
for(int i = 0; i < m; i++) {
char c;
cin >> c; cin.ignore();
if(conv[c])
cout << (char)conv[c];
else
cout << c;
}
cout << endl;
}
}
``` |
#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
int main() {
int n;
while (cin >> n, n) {
map<char, char>mp;
rep(i, n) {
char c, d; cin >> c >> d;
mp[c] = d;
}
int m; cin >> m;
string s = "";
rep(i, m) {
char c; cin >> c;
if (mp[c] == 0)s += c;
else s += mp[c];
}
cout << s << endl;
}
return 0;
} | ### Prompt
Create a solution in cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
int main() {
int n;
while (cin >> n, n) {
map<char, char>mp;
rep(i, n) {
char c, d; cin >> c >> d;
mp[c] = d;
}
int m; cin >> m;
string s = "";
rep(i, m) {
char c; cin >> c;
if (mp[c] == 0)s += c;
else s += mp[c];
}
cout << s << endl;
}
return 0;
}
``` |
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
long long i,j,n,m;
cin >> n;
while(n){
char c[2][n],p;
for(i=0;i<n;i++) cin >> c[0][i] >> c[1][i];
cin >> m;
for(i=0;i<m;i++) {
cin >> p;
for(j=0;j<n;j++) if(p==c[0][j]){p=c[1][j]; break;}
cout << p;
}
cout << endl;
cin >> n;
}
return 0;
} | ### Prompt
Please provide a Cpp coded solution to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
long long i,j,n,m;
cin >> n;
while(n){
char c[2][n],p;
for(i=0;i<n;i++) cin >> c[0][i] >> c[1][i];
cin >> m;
for(i=0;i<m;i++) {
cin >> p;
for(j=0;j<n;j++) if(p==c[0][j]){p=c[1][j]; break;}
cout << p;
}
cout << endl;
cin >> n;
}
return 0;
}
``` |
#include <stdio.h>
int main(){
int n,m;
char c[2],a[128];
while(1){
scanf("%d",&n);
if(n==0)return 0;
for(int i=0;i<128;i++)a[i]=i;
for(int i=0;i<n;i++){
scanf("%s %s",&c[0],&c[1]);
a[c[0]]=c[1];
}
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%s",&c[0]);
printf("%c",a[c[0]]);
}
printf("\n");
}
} | ### Prompt
Your task is to create a CPP solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <stdio.h>
int main(){
int n,m;
char c[2],a[128];
while(1){
scanf("%d",&n);
if(n==0)return 0;
for(int i=0;i<128;i++)a[i]=i;
for(int i=0;i<n;i++){
scanf("%s %s",&c[0],&c[1]);
a[c[0]]=c[1];
}
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%s",&c[0]);
printf("%c",a[c[0]]);
}
printf("\n");
}
}
``` |
#include <cstdio>
int main()
{
while(true) {
int n, m;
char table[256];
for(int i = 0; i < 256; ++i)
table[i] = i;
scanf("%d", &n);
if(n == 0)
break;
for(int i = 0; i < n; ++i) {
char a[16], b[16];
scanf("%s%s", a, b);
table[a[0]] = b[0];
}
scanf("%d", &m);
for(int i = 0; i < m; ++i) {
char c[16];
scanf("%s", c);
printf("%c", table[c[0]]);
}
printf("\n");
}
return 0;
} | ### Prompt
Please formulate a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <cstdio>
int main()
{
while(true) {
int n, m;
char table[256];
for(int i = 0; i < 256; ++i)
table[i] = i;
scanf("%d", &n);
if(n == 0)
break;
for(int i = 0; i < n; ++i) {
char a[16], b[16];
scanf("%s%s", a, b);
table[a[0]] = b[0];
}
scanf("%d", &m);
for(int i = 0; i < m; ++i) {
char c[16];
scanf("%s", c);
printf("%c", table[c[0]]);
}
printf("\n");
}
return 0;
}
``` |
#include <cstdio>
#include <iostream>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
int main(){
int n;
while(cin >> n ,n){
char table[128];
rep(i,128)table[i] = i;
rep(i,n){
char a,b;
cin >> a >> b;
table[a] = b;
}
int m; cin >> m;
rep(i,m){
char c;
cin >> c;
putchar(table[c]);
}
puts("");
}
} | ### Prompt
Create a solution in Cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <cstdio>
#include <iostream>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
int main(){
int n;
while(cin >> n ,n){
char table[128];
rep(i,128)table[i] = i;
rep(i,n){
char a,b;
cin >> a >> b;
table[a] = b;
}
int m; cin >> m;
rep(i,m){
char c;
cin >> c;
putchar(table[c]);
}
puts("");
}
}
``` |
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
map<char, char> mp;
char a,b,c;
string x;
int n;
cin >> n;
do{
mp.clear();
x.clear();
do{
cin >> a >> b;
mp[a] = b;
} while (--n);
cin >> n;
do{
cin >> c;
if (mp[c] != NULL) {
x += mp[c];
}
else {
x += c;
}
} while (--n);
cout << x << endl;
} while (cin >> n, n != 0);
return 0;
} | ### Prompt
Create a solution in Cpp for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
map<char, char> mp;
char a,b,c;
string x;
int n;
cin >> n;
do{
mp.clear();
x.clear();
do{
cin >> a >> b;
mp[a] = b;
} while (--n);
cin >> n;
do{
cin >> c;
if (mp[c] != NULL) {
x += mp[c];
}
else {
x += c;
}
} while (--n);
cout << x << endl;
} while (cin >> n, n != 0);
return 0;
}
``` |
#include<iostream>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
char m[99][2],z,y;
int main(){
int s,n;
while(true){
cin>>s;
if(s==0)break;
rep(i,s)cin>>m[i][0]>>m[i][1];
cin>>n;
rep(i,n){
cin>>z;
y=z;
rep(j,s)if(m[j][0]==z)y=m[j][1];
cout<<y;
}
cout<<endl;
}
return 0;
} | ### Prompt
Please provide a CPP coded solution to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
char m[99][2],z,y;
int main(){
int s,n;
while(true){
cin>>s;
if(s==0)break;
rep(i,s)cin>>m[i][0]>>m[i][1];
cin>>n;
rep(i,n){
cin>>z;
y=z;
rep(j,s)if(m[j][0]==z)y=m[j][1];
cout<<y;
}
cout<<endl;
}
return 0;
}
``` |
#include <map>
#include <string>
#include <stdio.h>
#include <iostream>
using namespace std;
int n, m;
int i, j;
char a, b, c;
char list[1000];
int main()
{
while (1)
{
scanf("%d", &n);
if (n==0) return 0;
for (i=0; i<1000; i++) list[i] = i;
for (i=0; i<n; i++)
{
scanf(" %c %c", &a, &b);
list[a] = b;
}
scanf("%d", &m);
for (i=0; i<m; i++)
{
scanf(" %c", &c);
printf("%c", list[c]);
}
printf("\n");
}
} | ### Prompt
In cpp, your task is to solve the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <map>
#include <string>
#include <stdio.h>
#include <iostream>
using namespace std;
int n, m;
int i, j;
char a, b, c;
char list[1000];
int main()
{
while (1)
{
scanf("%d", &n);
if (n==0) return 0;
for (i=0; i<1000; i++) list[i] = i;
for (i=0; i<n; i++)
{
scanf(" %c %c", &a, &b);
list[a] = b;
}
scanf("%d", &m);
for (i=0; i<m; i++)
{
scanf(" %c", &c);
printf("%c", list[c]);
}
printf("\n");
}
}
``` |
#include <iostream>
#include <algorithm>
using namespace std;
int main(void){
int n;
while(cin >> n , n){
char dic[256];
fill(dic , dic + 256 , 0);
for(int i = 0; i < n; i++){
char c;
cin >> c;
cin >> dic[c];
}
int m;
cin >> m;
for(int i = 0; i < m; i++){
char c;
cin >> c;
if(dic[c] == 0){
cout << c;
} else {
cout << dic[c];
}
}
cout << endl;
}
return 0;
} | ### Prompt
Create a solution in CPP for the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main(void){
int n;
while(cin >> n , n){
char dic[256];
fill(dic , dic + 256 , 0);
for(int i = 0; i < n; i++){
char c;
cin >> c;
cin >> dic[c];
}
int m;
cin >> m;
for(int i = 0; i < m; i++){
char c;
cin >> c;
if(dic[c] == 0){
cout << c;
} else {
cout << dic[c];
}
}
cout << endl;
}
return 0;
}
``` |
#include <iostream>
using namespace std;
#define repi(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,n) for(int i=0;i<(n);i++)
int main() {
ios::sync_with_stdio(false);
int n, m;
while(cin>>n,n) {
char t[256] = {};
char a, b;
rep(i, n) {
cin>>a>>b;
t[a] = b;
}
cin>>m;
rep(i, m) {
cin>>a;
if(t[a]==0)cout<<a;
else cout<<t[a];
}
cout<<endl;
}
return 0;
} | ### Prompt
Generate a cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
using namespace std;
#define repi(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,n) for(int i=0;i<(n);i++)
int main() {
ios::sync_with_stdio(false);
int n, m;
while(cin>>n,n) {
char t[256] = {};
char a, b;
rep(i, n) {
cin>>a>>b;
t[a] = b;
}
cin>>m;
rep(i, m) {
cin>>a;
if(t[a]==0)cout<<a;
else cout<<t[a];
}
cout<<endl;
}
return 0;
}
``` |
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
while(1){
int n,m;
char secret;
char A[100]={0},B[100]={0};
cin>>n;
if(n==0)return 0;
for(int i=0;i<n;i++){
cin>>A[i]>>B[i];
}
cin>>m;
for(int i=0;i<m;i++){
cin>>secret;
int flag=0;
for(int j=0;j<n;j++){
if(secret==A[j]){
printf("%c",B[j]);
flag=1;
break;
}
}
if(flag==0)printf("%c",secret);
}
printf("\n");
}
} | ### Prompt
Please provide a CPP coded solution to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
while(1){
int n,m;
char secret;
char A[100]={0},B[100]={0};
cin>>n;
if(n==0)return 0;
for(int i=0;i<n;i++){
cin>>A[i]>>B[i];
}
cin>>m;
for(int i=0;i<m;i++){
cin>>secret;
int flag=0;
for(int j=0;j<n;j++){
if(secret==A[j]){
printf("%c",B[j]);
flag=1;
break;
}
}
if(flag==0)printf("%c",secret);
}
printf("\n");
}
}
``` |
#include <cstdio>
#include <map>
using namespace std;
int main()
{
int n;
while(scanf("%d\n", &n), n){
map<char, char> m;
char a, b;
for(int i = 0; i < n; i++){
scanf("%c %c\n", &a, &b);
m[a] = b;
}
scanf("%d\n", &n);
for(int i = 0; i < n; i++){
scanf("%c\n", &a);
putchar(m[a] ? m[a] : a);
}
putchar('\n');
}
return 0;
} | ### Prompt
Please create a solution in Cpp to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <cstdio>
#include <map>
using namespace std;
int main()
{
int n;
while(scanf("%d\n", &n), n){
map<char, char> m;
char a, b;
for(int i = 0; i < n; i++){
scanf("%c %c\n", &a, &b);
m[a] = b;
}
scanf("%d\n", &n);
for(int i = 0; i < n; i++){
scanf("%c\n", &a);
putchar(m[a] ? m[a] : a);
}
putchar('\n');
}
return 0;
}
``` |
#include <iostream>
#include <map>
using namespace std;
int main(){
int n;
char buf;
map<char, char> conv;
while(1){
cin >> n;
if(n != 0){
conv.clear();
for(int i = 0; i < n; i++){
cin >> buf;
cin >> conv[buf];
}
cin >> n;
for(int i = 0; i < n; i++){
cin >> buf;
if(conv.count(buf)){
cout << conv[buf];
}else{
cout << buf;
}
}
cout << endl;
}else{
break;
}
}
return 0;
} | ### Prompt
Generate a Cpp solution to the following problem:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include <iostream>
#include <map>
using namespace std;
int main(){
int n;
char buf;
map<char, char> conv;
while(1){
cin >> n;
if(n != 0){
conv.clear();
for(int i = 0; i < n; i++){
cin >> buf;
cin >> conv[buf];
}
cin >> n;
for(int i = 0; i < n; i++){
cin >> buf;
if(conv.count(buf)){
cout << conv[buf];
}else{
cout << buf;
}
}
cout << endl;
}else{
break;
}
}
return 0;
}
``` |
#include<iostream>
using namespace std;
int main() {
int i,j,k;
string s;
while(1){
cin>>i;
if(i==0)break;
string c[i][2];
for(j=0;j<i;j++) {
cin>>s,c[j][0]=s;
cin>>s,c[j][1]=s;
}
cin>>k;
for(j=0;j<k;j++){
cin>>s;
for(int l=0;l<i;l++){
if(s==c[l][0]) {
s=c[l][1];
break;
}
}
cout<<s;
}
cout<<"\n";
}
} | ### Prompt
Develop a solution in cpp to the problem described below:
Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
### Response
```cpp
#include<iostream>
using namespace std;
int main() {
int i,j,k;
string s;
while(1){
cin>>i;
if(i==0)break;
string c[i][2];
for(j=0;j<i;j++) {
cin>>s,c[j][0]=s;
cin>>s,c[j][1]=s;
}
cin>>k;
for(j=0;j<k;j++){
cin>>s;
for(int l=0;l<i;l++){
if(s==c[l][0]) {
s=c[l][1];
break;
}
}
cout<<s;
}
cout<<"\n";
}
}
``` |
#include<bits/stdc++.h>
using namespace std;
const double EPS = 1e-8, PI = acos(-1), INF = 1e9;
inline bool eq(double a, double b)
{
return abs(b - a) < EPS;
}
struct Point
{
double x, y;
Point() {};
Point(double x, double y) : x(x), y(y) {};
Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
Point operator*(const double b) const { return Point(x * b, y * b); }
Point operator*(const Point &b) const { return Point(x * b.x - y * b.y, x * b.y + y * b.x); }
Point operator/(const double b) const { return Point(x / b, y / b); }
bool operator<(const Point &b) const { return x != b.x ? x < b.x : y < b.y; }
bool operator==(const Point &b) const { return eq(x, b.x) && eq(y, b.y); }
double norm() { return x * x + y * y; }
double arg() { return atan2(x, y); }
double abs() { return sqrt(norm()); }
Point rotate(double theta) { return Point(cos(theta) * x - sin(theta) * y, sin(theta) * x + cos(theta) * y); }
Point rotate90() { return Point(-y, x); }
friend ostream &operator<<(ostream &os, Point &p) { return os << "(" << p.x << "," << p.y << ")"; }
friend istream &operator>>(istream &is, Point &a) { return is >> a.x >> a.y; }
};
double cross(const Point &a, const Point &b)
{
return a.x * b.y - a.y * b.x;
}
double dot(const Point &a, const Point &b)
{
return a.x * b.x + a.y * b.y;
}
double RadianToDegree(double r)
{
return (r * 180.0 / acos(-1));
}
double DegreeToRadian(double d)
{
return (d * acos(-1) / 180.0);
}
double GetAngle(const Point &a, const Point &b, const Point &c)
{
const Point v = b - a, w = c - b;
double alpha = atan2(v.y, v.x), beta = atan2(w.y, w.x);
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
int ccw(const Point &a, Point b, Point c)
{
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1;
if(cross(b, c) < -EPS) return -1;
if(dot(b, c) < 0) return +2;
if(b.norm() < c.norm()) return -2;
return 0;
}
struct Segment
{
Point a, b;
Segment() {};
Segment(Point a, Point b) : a(a), b(b) {};
friend ostream &operator<<(ostream &os, Segment &p) { return os << "(" << p.a.x << "," << p.a.y << ") to (" << p.b.x << "," << p.b.y << ")"; }
friend istream &operator>>(istream &is, Segment &a) { return is >> a.a.x >> a.a.y >> a.b.x >> a.b.y; }
};
bool Intersect(const Segment &s, const Point &p)
{
return ccw(s.a, s.b, p) == 0;
}
bool Intersect(const Segment &s, const Segment &t)
{
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&
ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
Point Crosspoint(const Segment &l, const Segment &m)
{
double A = cross(l.b - l.a, m.b - m.a);
double B = cross(l.b - l.a, l.b - m.a);
if(abs(A) < EPS && abs(B) < EPS) return m.a; // same line
return m.a + (m.b - m.a) * B / A;
}
vector< vector< int > > SegmentArrangement(vector< Segment > &segs, vector< Point > &ps)
{
vector< vector< int > > g;
ps.clear();
const int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(Intersect(segs[i], segs[j])) {
ps.emplace_back(Crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
const int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(Intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
double Dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps)
{
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< double > > min_cost(g.size(), vector< double >(g.size(), INF));
typedef tuple< double, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
double cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + RadianToDegree(GetAngle(ps[pre], ps[cur], ps[to]));
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main()
{
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
auto g = SegmentArrangement(segs, ps);
double ret = Dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
} | ### Prompt
Develop a solution in cpp to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
const double EPS = 1e-8, PI = acos(-1), INF = 1e9;
inline bool eq(double a, double b)
{
return abs(b - a) < EPS;
}
struct Point
{
double x, y;
Point() {};
Point(double x, double y) : x(x), y(y) {};
Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
Point operator*(const double b) const { return Point(x * b, y * b); }
Point operator*(const Point &b) const { return Point(x * b.x - y * b.y, x * b.y + y * b.x); }
Point operator/(const double b) const { return Point(x / b, y / b); }
bool operator<(const Point &b) const { return x != b.x ? x < b.x : y < b.y; }
bool operator==(const Point &b) const { return eq(x, b.x) && eq(y, b.y); }
double norm() { return x * x + y * y; }
double arg() { return atan2(x, y); }
double abs() { return sqrt(norm()); }
Point rotate(double theta) { return Point(cos(theta) * x - sin(theta) * y, sin(theta) * x + cos(theta) * y); }
Point rotate90() { return Point(-y, x); }
friend ostream &operator<<(ostream &os, Point &p) { return os << "(" << p.x << "," << p.y << ")"; }
friend istream &operator>>(istream &is, Point &a) { return is >> a.x >> a.y; }
};
double cross(const Point &a, const Point &b)
{
return a.x * b.y - a.y * b.x;
}
double dot(const Point &a, const Point &b)
{
return a.x * b.x + a.y * b.y;
}
double RadianToDegree(double r)
{
return (r * 180.0 / acos(-1));
}
double DegreeToRadian(double d)
{
return (d * acos(-1) / 180.0);
}
double GetAngle(const Point &a, const Point &b, const Point &c)
{
const Point v = b - a, w = c - b;
double alpha = atan2(v.y, v.x), beta = atan2(w.y, w.x);
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
int ccw(const Point &a, Point b, Point c)
{
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1;
if(cross(b, c) < -EPS) return -1;
if(dot(b, c) < 0) return +2;
if(b.norm() < c.norm()) return -2;
return 0;
}
struct Segment
{
Point a, b;
Segment() {};
Segment(Point a, Point b) : a(a), b(b) {};
friend ostream &operator<<(ostream &os, Segment &p) { return os << "(" << p.a.x << "," << p.a.y << ") to (" << p.b.x << "," << p.b.y << ")"; }
friend istream &operator>>(istream &is, Segment &a) { return is >> a.a.x >> a.a.y >> a.b.x >> a.b.y; }
};
bool Intersect(const Segment &s, const Point &p)
{
return ccw(s.a, s.b, p) == 0;
}
bool Intersect(const Segment &s, const Segment &t)
{
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&
ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
Point Crosspoint(const Segment &l, const Segment &m)
{
double A = cross(l.b - l.a, m.b - m.a);
double B = cross(l.b - l.a, l.b - m.a);
if(abs(A) < EPS && abs(B) < EPS) return m.a; // same line
return m.a + (m.b - m.a) * B / A;
}
vector< vector< int > > SegmentArrangement(vector< Segment > &segs, vector< Point > &ps)
{
vector< vector< int > > g;
ps.clear();
const int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(Intersect(segs[i], segs[j])) {
ps.emplace_back(Crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
const int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(Intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
double Dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps)
{
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< double > > min_cost(g.size(), vector< double >(g.size(), INF));
typedef tuple< double, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
double cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + RadianToDegree(GetAngle(ps[pre], ps[cur], ps[to]));
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main()
{
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
auto g = SegmentArrangement(segs, ps);
double ret = Dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
}
``` |
#include <bits/stdc++.h>
using namespace std;
#define EPS (1e-5)
#define equal(a,b) (fabs(a-b) < EPS)
#define lt(a,b) (a-b < -EPS)
#define MAX 252
#define INF (1e9)
#define PI acos(-1)
struct Point{
long double x,y;
Point(){}
Point(long double x,long double y) : x(x),y(y) {}
Point operator + (const Point &p)const{ return Point(x+p.x,y+p.y); }
Point operator - (const Point &p)const{ return Point(x-p.x,y-p.y); }
Point operator * (const long double &k)const{ return Point(x*k,y*k); }
Point operator / (const long double &k)const{ return Point(x/k,y/k); }
bool operator < (const Point &p)const{ return x != p.x ? x < p.x : y < p.y; }
bool operator == (const Point &p)const{ return (x == p.x && y == p.y); }
};
long double dot(const Point &a,const Point &b){ return a.x*b.x+a.y*b.y; }
long double cross(const Point &a,const Point &b){ return a.x*b.y - b.x*a.y; }
long double norm(const Point &p){ return dot(p,p); }
long double abs(const Point &p){ return sqrt(norm(p)); }
long double dist(const Point &a,const Point &b){
return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2));
}
long double toRad(long double ang){ return ang*PI/180; }
long double toAng(long double rad){ return rad*180/PI; }
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
typedef Point Vector;
int ccw(const Point &p0,const Point &p1,const Point &p2){
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a,b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS) return CLOCKWISE;
if(dot(a,b) < -EPS) return ONLINE_BACK;
if(norm(a) < norm(b)) return ONLINE_FRONT;
return ON_SEGMENT;
}
long double getAngle(const Point &a,const Point &b,const Point &c){
Vector v1 = b-a, v2 = c-b;
long double aa = atan2(v1.x,v1.y),ba = atan2(v2.x,v2.y);
if(aa > ba) swap(aa,ba);
long double ang = toAng(ba - aa);
return min(ang,360-ang);
}
struct Segment{
Point s,t;
Segment(){}
Segment(Point s,Point t) : s(s),t(t) {}
};
bool isIntersectSP(const Segment &s,const Point &p){
return (ccw(s.s,s.t,p) == 0);
}
bool isIntersectSS(const Segment &a,const Segment &b){
Point s[2] = {a.s,a.t}, t[2] = {b.s,b.t};
return (ccw(s[0],s[1],t[0])*ccw(s[0],s[1],t[1]) <= 0 &&
ccw(t[0],t[1],s[0])*ccw(t[0],t[1],s[1]) <= 0);
}
Point crosspointSS(const Segment &a,const Segment &b){
Vector va = a.t-a.s, vb = b.t-b.s;
long double d = cross(vb,va);
if(abs(d) < EPS) return b.s;
return a.s+va*cross(vb,b.t-a.s)*(1.0/d);
}
typedef vector<int> Edges;
typedef vector<Edges> Graph;
Graph segmentArrangement(vector<Segment> &segs,vector<Point> &ps){
Graph G;
int N = segs.size();
ps.clear();
for(int i = 0 ; i < N ; i++){
ps.push_back(segs[i].s);
ps.push_back(segs[i].t);
for(int j = i+1 ; j < N ; j++){
if(isIntersectSS(segs[i],segs[j])){
ps.push_back(crosspointSS(segs[i],segs[j]));
}
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
int N2 = ps.size();
G.resize(N2);
for(int i = 0 ; i < N ; i++){
vector<int> vec;
for(int j = 0 ; j < N2 ; j++){
if(isIntersectSP(segs[i],ps[j])){
vec.push_back(j);
}
}
sort(vec.begin(),vec.end());
for(int j = 0 ; j < (int)vec.size()-1 ; j++){
int u = vec[j], v = vec[j+1];
G[u].push_back(v);
G[v].push_back(u);
}
}
return G;
}
struct State{
long double w;
int p,n;
State(){}
State(long double w,int p,int n) :
w(w),p(p),n(n) {}
bool operator < (const State &s)const{
return w > s.w;
}
};
long double dijkstra(Graph &G,Point &s,Point &t,vector<Point> &ps){
int idx = -1;
for(int i = 0 ; i < (int)ps.size() ; i++){
if(ps[i] == s){
idx = i;
}
}
long double d[MAX][MAX];
for(int i = 0 ; i < MAX ; i++){
for(int j = 0 ; j < MAX ; j++){
d[i][j] = INF;
}
}
priority_queue<State> Q;
for(int i = 0 ; i < (int)G[idx].size() ; i++){
int to = G[idx][i];
Q.push(State(0,idx,to));
d[idx][to] = 0;
}
while(!Q.empty()){
State st = Q.top(); Q.pop();
int p = st.p,n = st.n;
long double w = st.w;
if(lt(d[p][n],w)) continue;
Point p1 = ps[p],p2 = ps[n];
if(p2 == t) return d[p][n];
for(int i = 0 ; i < (int)G[n].size() ; i++){
int to = G[n][i];
if(p == to) continue;
Point p3 = ps[to];
long double ncost = w + getAngle(p1,p2,p3);
if(ncost < d[n][to] && !equal(ncost,d[n][to])){
d[n][to] = ncost;
Q.push(State(d[n][to],n,to));
}
}
}
return INF;
}
int main(){
int N;
while(cin >> N, N){
Point s,t;
vector<Segment> segs(N);
for(int i = 0 ; i < N ; i++){
cin >> segs[i].s.x >> segs[i].s.y;
cin >> segs[i].t.x >> segs[i].t.y;
}
cin >> s.x >> s.y >> t.x >> t.y;
vector<Point> ps;
Graph G = segmentArrangement(segs,ps);
long double res = dijkstra(G,s,t,ps);
if(res == INF){
cout << -1 << endl;
}else{
printf("%.12Lf\n",res);
}
}
return 0;
} | ### Prompt
Create a solution in CPP for the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define EPS (1e-5)
#define equal(a,b) (fabs(a-b) < EPS)
#define lt(a,b) (a-b < -EPS)
#define MAX 252
#define INF (1e9)
#define PI acos(-1)
struct Point{
long double x,y;
Point(){}
Point(long double x,long double y) : x(x),y(y) {}
Point operator + (const Point &p)const{ return Point(x+p.x,y+p.y); }
Point operator - (const Point &p)const{ return Point(x-p.x,y-p.y); }
Point operator * (const long double &k)const{ return Point(x*k,y*k); }
Point operator / (const long double &k)const{ return Point(x/k,y/k); }
bool operator < (const Point &p)const{ return x != p.x ? x < p.x : y < p.y; }
bool operator == (const Point &p)const{ return (x == p.x && y == p.y); }
};
long double dot(const Point &a,const Point &b){ return a.x*b.x+a.y*b.y; }
long double cross(const Point &a,const Point &b){ return a.x*b.y - b.x*a.y; }
long double norm(const Point &p){ return dot(p,p); }
long double abs(const Point &p){ return sqrt(norm(p)); }
long double dist(const Point &a,const Point &b){
return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2));
}
long double toRad(long double ang){ return ang*PI/180; }
long double toAng(long double rad){ return rad*180/PI; }
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
typedef Point Vector;
int ccw(const Point &p0,const Point &p1,const Point &p2){
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a,b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS) return CLOCKWISE;
if(dot(a,b) < -EPS) return ONLINE_BACK;
if(norm(a) < norm(b)) return ONLINE_FRONT;
return ON_SEGMENT;
}
long double getAngle(const Point &a,const Point &b,const Point &c){
Vector v1 = b-a, v2 = c-b;
long double aa = atan2(v1.x,v1.y),ba = atan2(v2.x,v2.y);
if(aa > ba) swap(aa,ba);
long double ang = toAng(ba - aa);
return min(ang,360-ang);
}
struct Segment{
Point s,t;
Segment(){}
Segment(Point s,Point t) : s(s),t(t) {}
};
bool isIntersectSP(const Segment &s,const Point &p){
return (ccw(s.s,s.t,p) == 0);
}
bool isIntersectSS(const Segment &a,const Segment &b){
Point s[2] = {a.s,a.t}, t[2] = {b.s,b.t};
return (ccw(s[0],s[1],t[0])*ccw(s[0],s[1],t[1]) <= 0 &&
ccw(t[0],t[1],s[0])*ccw(t[0],t[1],s[1]) <= 0);
}
Point crosspointSS(const Segment &a,const Segment &b){
Vector va = a.t-a.s, vb = b.t-b.s;
long double d = cross(vb,va);
if(abs(d) < EPS) return b.s;
return a.s+va*cross(vb,b.t-a.s)*(1.0/d);
}
typedef vector<int> Edges;
typedef vector<Edges> Graph;
Graph segmentArrangement(vector<Segment> &segs,vector<Point> &ps){
Graph G;
int N = segs.size();
ps.clear();
for(int i = 0 ; i < N ; i++){
ps.push_back(segs[i].s);
ps.push_back(segs[i].t);
for(int j = i+1 ; j < N ; j++){
if(isIntersectSS(segs[i],segs[j])){
ps.push_back(crosspointSS(segs[i],segs[j]));
}
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
int N2 = ps.size();
G.resize(N2);
for(int i = 0 ; i < N ; i++){
vector<int> vec;
for(int j = 0 ; j < N2 ; j++){
if(isIntersectSP(segs[i],ps[j])){
vec.push_back(j);
}
}
sort(vec.begin(),vec.end());
for(int j = 0 ; j < (int)vec.size()-1 ; j++){
int u = vec[j], v = vec[j+1];
G[u].push_back(v);
G[v].push_back(u);
}
}
return G;
}
struct State{
long double w;
int p,n;
State(){}
State(long double w,int p,int n) :
w(w),p(p),n(n) {}
bool operator < (const State &s)const{
return w > s.w;
}
};
long double dijkstra(Graph &G,Point &s,Point &t,vector<Point> &ps){
int idx = -1;
for(int i = 0 ; i < (int)ps.size() ; i++){
if(ps[i] == s){
idx = i;
}
}
long double d[MAX][MAX];
for(int i = 0 ; i < MAX ; i++){
for(int j = 0 ; j < MAX ; j++){
d[i][j] = INF;
}
}
priority_queue<State> Q;
for(int i = 0 ; i < (int)G[idx].size() ; i++){
int to = G[idx][i];
Q.push(State(0,idx,to));
d[idx][to] = 0;
}
while(!Q.empty()){
State st = Q.top(); Q.pop();
int p = st.p,n = st.n;
long double w = st.w;
if(lt(d[p][n],w)) continue;
Point p1 = ps[p],p2 = ps[n];
if(p2 == t) return d[p][n];
for(int i = 0 ; i < (int)G[n].size() ; i++){
int to = G[n][i];
if(p == to) continue;
Point p3 = ps[to];
long double ncost = w + getAngle(p1,p2,p3);
if(ncost < d[n][to] && !equal(ncost,d[n][to])){
d[n][to] = ncost;
Q.push(State(d[n][to],n,to));
}
}
}
return INF;
}
int main(){
int N;
while(cin >> N, N){
Point s,t;
vector<Segment> segs(N);
for(int i = 0 ; i < N ; i++){
cin >> segs[i].s.x >> segs[i].s.y;
cin >> segs[i].t.x >> segs[i].t.y;
}
cin >> s.x >> s.y >> t.x >> t.y;
vector<Point> ps;
Graph G = segmentArrangement(segs,ps);
long double res = dijkstra(G,s,t,ps);
if(res == INF){
cout << -1 << endl;
}else{
printf("%.12Lf\n",res);
}
}
return 0;
}
``` |
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include<cassert>
#include<iomanip>
#include<queue>
#include<cstdio>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define inf (1<<29)
#define EPS (1e-10)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define pow2(a) ((a)*(a))
using namespace std;
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
class Point
{
public:
double x,y;
Point(double x = -inf,double y = -inf): x(x),y(y){}
Point operator + (Point p){return Point(x+p.x,y+p.y);}
Point operator - (Point p){return Point(x-p.x,y-p.y);}
Point operator * (double a){return Point(a*x,a*y);}
Point operator / (double a){return Point(x/a,y/a);}
bool operator < (const Point& p) const
{
return !equals(x,p.x)?x<p.x:y<p.y;
}
bool operator == (const Point& p)const
{
return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS;
}
};
struct Segment
{
Point p1,p2;
Segment(Point p1 = Point(-inf,-inf),Point p2 = Point(-inf,-inf)):p1(p1),p2(p2){}
bool operator == (const Segment& p)const
{
return p.p1 == p1 && p.p2 == p2;
}
};
typedef Point Vector;
typedef Segment Line;
typedef vector<Point> Polygon;
ostream& operator << (ostream& os,const Point& a)
{
os << "(" << a.x << "," << a.y << ")";
}
ostream& operator << (ostream& os,const Segment& a)
{
os << "( " << a.p1 << " , " << a.p2 << " )";
}
double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; }
double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; }
double norm(Point a){ return a.x*a.x+a.y*a.y; }
double abs(Point a){ return sqrt(norm(a)); }
//rad は角度をラジアンで持たせること
Point rotate(Point a,double rad){ return Point(cos(rad)*a.x - sin(rad)*a.y,sin(rad)*a.x + cos(rad)*a.y); }
// 度をラジアンに変換
double toRad(double agl){ return agl*M_PI/180.0; }
int ccw(Point p0,Point p1,Point p2)
{
Point a = p1-p0;
Point b = p2-p0;
if(cross(a,b) > EPS)return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS)return CLOCKWISE;
if(dot(a,b) < -EPS)return ONLINE_BACK;
if(norm(a) < norm(b))return ONLINE_FRONT;
return ON_SEGMENT;
}
bool merge_if_able(Segment &s, Segment t) {
if (abs(cross(s.p2-s.p1, t.p2-t.p1)) > EPS) return false;
if (ccw(s.p1, t.p1, s.p2) == +1 ||
ccw(s.p1, t.p1, s.p2) == -1) return false; // not on the same line
if (ccw(s.p1, s.p2, t.p1) == -2 ||
ccw(t.p1, t.p2, s.p1) == -2) return false; // separated
s = Segment(min(s.p1, t.p1), max(s.p2, t.p2));
return true;
}
void merge_segments(vector<Segment>& segs) {
for (int i = 0; i < segs.size(); ++i)
if (segs[i].p2 < segs[i].p1)
swap(segs[i].p2, segs[i].p1);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
bool intersectLL(Line l, Line m) {
return abs(cross(l.p2-l.p1, m.p2-m.p1)) > EPS || // non-parallel
abs(cross(l.p2-l.p1, m.p1-l.p1)) < EPS; // same line
}
bool intersectLS(Line l, Line s) {
return cross(l.p2-l.p1, s.p1-l.p1)* // s[0] is left of l
cross(l.p2-l.p1, s.p2-l.p1) < EPS; // s[1] is right of l
}
bool intersectLP(Line l,Point p) {
return abs(cross(l.p2-p, l.p1-p)) < EPS;
}
bool intersectSS(Line s, Line t) {
return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 &&
ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0;
}
bool intersectSP(Line s, Point p) {
return abs(s.p1-p)+abs(s.p2-p)-abs(s.p2-s.p1) < EPS; // triangle inequality
}
Point projection(Line l,Point p) {
double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2);
return l.p1 + (l.p1-l.p2)*t;
}
Point reflection(Line l,Point p) {
return p + (projection(l, p) - p) * 2;
}
double distanceLP(Line l, Point p) {
return abs(p - projection(l, p));
}
double distanceLL(Line l, Line m) {
return intersectLL(l, m) ? 0 : distanceLP(l, m.p1);
}
double distanceLS(Line l, Line s) {
if (intersectLS(l, s)) return 0;
return min(distanceLP(l, s.p1), distanceLP(l, s.p2));
}
double distanceSP(Line s, Point p) {
Point r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s.p1 - p), abs(s.p2 - p));
}
double distanceSS(Line s, Line t) {
if (intersectSS(s, t)) return 0;
return min(min(distanceSP(s, t.p1), distanceSP(s, t.p2)),
min(distanceSP(t, s.p1), distanceSP(t, s.p2)));
}
Point crosspoint(Line l, Line m) {
double A = cross(l.p2 - l.p1, m.p2 - m.p1);
double B = cross(l.p2 - l.p1, l.p2 - m.p1);
if (abs(A) < EPS && abs(B) < EPS) return m.p1; // same line
if (abs(A) < EPS) assert(false); // !!!PRECONDITION NOT SATISFIED!!!
return m.p1 + (m.p2 - m.p1) * (B / A);
}
struct Edge
{
int from,to;
double cost;
Edge(int from=inf,int to=inf,double cost=inf):from(from),to(to),cost(cost){}
bool operator < (const Edge& a)const
{
return cost < a.cost;
}
};
typedef vector<Edge> vE;
typedef vector<vE> vvE;
Point star,dest;
vector<vector<Edge> > segmentArrangement(vector<Segment> vs,vector<Point> &ps)
{
/*
端点もいれたいなら
ここであらかじめ端点だけpsにいれる
*/
rep(i,vs.size())
REP(j,i+1,vs.size())
if(intersectSS(vs[i],vs[j]))
ps.push_back(Point(crosspoint(vs[i],vs[j])));
//
ps.push_back(star);
ps.push_back(dest);
//
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
vector<vector<Edge> > ret(ps.size());
for(int i=0;i<vs.size();i++)
{
vector<pair<double,int> > list;
rep(j,ps.size())
if(intersectSP(vs[i],ps[j]))
list.push_back(pair<double,int>(norm(vs[i].p1-ps[j]),j));
sort(list.begin(),list.end());
//for(int j=0;j<list.size()-1;++j) is not good
for(int j=0;j+1<list.size();++j)
{
int from = list[j].second, to = list[j+1].second;
double cost = abs(ps[from]-ps[to]);
ret[from].push_back(Edge(from,to,cost));
ret[to].push_back(Edge(to,from,cost));
}
}
return ret;
}
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
struct Pox
{
int prev,cur;
double cost;
Pox(int prev=inf,int cur=inf,double cost=inf):prev(prev),cur(cur),cost(cost){}
bool operator < (const Pox& a)const
{
return cost > a.cost;
}
};
int n;
double calcCost(Point A,Point B,Point C)
{
double a = sqrt(pow2(B.x-C.x)+pow2(B.y-C.y));
double b = sqrt(pow2(A.x-C.x)+pow2(A.y-C.y));
double c = sqrt(pow2(A.x-B.x)+pow2(A.y-B.y));
//cout << a << ",x," << b << ",x," << c << endl;
return acos((c*c+a*a-b*b)/(2.0*c*a))*180/M_PI;
}
void dijkstra(vvE &G,vector<Point> &ps)
{
int sp,ep;
sp = ep = inf;
rep(i,ps.size())
if(ps[i] == star)sp = i;
else if(ps[i] == dest)ep = i;
//cout << "sp = " << sp << " ep = " << ep << endl;
assert(sp != inf);
assert(ep != inf);
int N = ps.size();
double mincost[N][N];
rep(i,N)rep(j,N)mincost[i][j] = (i==j?0:inf);
priority_queue<Pox> Q;
Q.push(Pox(sp,sp,0));
//cout << "dijkstra----" << endl;
while(!Q.empty())
{
Pox pox = Q.top(); Q.pop();
//cout << "(" << pox.prev << "," << pox.cur << "," << pox.cost << ")" << endl;
if(pox.cur == ep)
{
printf("%.12lf\n",pox.cost);
//cout << setiosflags(ios::fixed) << setprecision(10) << pox.cost << endl;
return;
}
int prev = pox.prev;
int cur = pox.cur;
double cost = pox.cost;
rep(i,G[cur].size())
{
int next = G[cur][i].to;
if(prev == next)continue;
Point e = ps[prev] - ps[cur];
e = e/abs(e);
e = e*1000;
double arg = 180 - calcCost(ps[prev],ps[cur],ps[next]);
//cout << "arg = " << arg << endl;
if(intersectSP(Segment(ps[prev]-e,ps[cur]+e),ps[next]))arg = 0;
double ncost = cost + arg;
if(prev == cur)ncost = 0;
//cout << "from " << cur << " to " << next << " the cost = " << ncost << endl;
if(!equals(ncost,mincost[cur][next]) && mincost[cur][next] > ncost)
{
mincost[cur][next] = ncost;
Q.push(Pox(cur,next,ncost));
}
}
}
cout << -1 << endl;
}
void compute(vector<Segment>& vec)
{
vector<Point> ps;
vvE G = segmentArrangement(vec,ps);
/*
cout << "ps--------" << endl;
rep(i,ps.size())cout << "ps[" << i << "] = " << ps[i] << endl;
cout << endl;
cout << "G---------" << endl;
rep(i,G.size())
{
rep(j,G[i].size())
{
cout << "(" << G[i][j].from << "," << G[i][j].to << ") ";
}
cout << endl;
}
cout << endl;
*/
dijkstra(G,ps);
}
int main()
{
while(cin >> n,n)
{
vector<Segment> vec(n);
rep(i,n)
{
cin >> vec[i].p1.x >> vec[i].p1.y >> vec[i].p2.x >> vec[i].p2.y;
//vec[i].p1 = vec[i].p1 + 1000;
//vec[i].p2 = vec[i].p2 + 1000;
}
merge_segments(vec);
cin >> star.x >> star.y >> dest.x >> dest.y;
compute(vec);
}
return 0;
}
| ### Prompt
Your challenge is to write a Cpp solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include<cassert>
#include<iomanip>
#include<queue>
#include<cstdio>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define inf (1<<29)
#define EPS (1e-10)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define pow2(a) ((a)*(a))
using namespace std;
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
class Point
{
public:
double x,y;
Point(double x = -inf,double y = -inf): x(x),y(y){}
Point operator + (Point p){return Point(x+p.x,y+p.y);}
Point operator - (Point p){return Point(x-p.x,y-p.y);}
Point operator * (double a){return Point(a*x,a*y);}
Point operator / (double a){return Point(x/a,y/a);}
bool operator < (const Point& p) const
{
return !equals(x,p.x)?x<p.x:y<p.y;
}
bool operator == (const Point& p)const
{
return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS;
}
};
struct Segment
{
Point p1,p2;
Segment(Point p1 = Point(-inf,-inf),Point p2 = Point(-inf,-inf)):p1(p1),p2(p2){}
bool operator == (const Segment& p)const
{
return p.p1 == p1 && p.p2 == p2;
}
};
typedef Point Vector;
typedef Segment Line;
typedef vector<Point> Polygon;
ostream& operator << (ostream& os,const Point& a)
{
os << "(" << a.x << "," << a.y << ")";
}
ostream& operator << (ostream& os,const Segment& a)
{
os << "( " << a.p1 << " , " << a.p2 << " )";
}
double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; }
double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; }
double norm(Point a){ return a.x*a.x+a.y*a.y; }
double abs(Point a){ return sqrt(norm(a)); }
//rad は角度をラジアンで持たせること
Point rotate(Point a,double rad){ return Point(cos(rad)*a.x - sin(rad)*a.y,sin(rad)*a.x + cos(rad)*a.y); }
// 度をラジアンに変換
double toRad(double agl){ return agl*M_PI/180.0; }
int ccw(Point p0,Point p1,Point p2)
{
Point a = p1-p0;
Point b = p2-p0;
if(cross(a,b) > EPS)return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS)return CLOCKWISE;
if(dot(a,b) < -EPS)return ONLINE_BACK;
if(norm(a) < norm(b))return ONLINE_FRONT;
return ON_SEGMENT;
}
bool merge_if_able(Segment &s, Segment t) {
if (abs(cross(s.p2-s.p1, t.p2-t.p1)) > EPS) return false;
if (ccw(s.p1, t.p1, s.p2) == +1 ||
ccw(s.p1, t.p1, s.p2) == -1) return false; // not on the same line
if (ccw(s.p1, s.p2, t.p1) == -2 ||
ccw(t.p1, t.p2, s.p1) == -2) return false; // separated
s = Segment(min(s.p1, t.p1), max(s.p2, t.p2));
return true;
}
void merge_segments(vector<Segment>& segs) {
for (int i = 0; i < segs.size(); ++i)
if (segs[i].p2 < segs[i].p1)
swap(segs[i].p2, segs[i].p1);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
bool intersectLL(Line l, Line m) {
return abs(cross(l.p2-l.p1, m.p2-m.p1)) > EPS || // non-parallel
abs(cross(l.p2-l.p1, m.p1-l.p1)) < EPS; // same line
}
bool intersectLS(Line l, Line s) {
return cross(l.p2-l.p1, s.p1-l.p1)* // s[0] is left of l
cross(l.p2-l.p1, s.p2-l.p1) < EPS; // s[1] is right of l
}
bool intersectLP(Line l,Point p) {
return abs(cross(l.p2-p, l.p1-p)) < EPS;
}
bool intersectSS(Line s, Line t) {
return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 &&
ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0;
}
bool intersectSP(Line s, Point p) {
return abs(s.p1-p)+abs(s.p2-p)-abs(s.p2-s.p1) < EPS; // triangle inequality
}
Point projection(Line l,Point p) {
double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2);
return l.p1 + (l.p1-l.p2)*t;
}
Point reflection(Line l,Point p) {
return p + (projection(l, p) - p) * 2;
}
double distanceLP(Line l, Point p) {
return abs(p - projection(l, p));
}
double distanceLL(Line l, Line m) {
return intersectLL(l, m) ? 0 : distanceLP(l, m.p1);
}
double distanceLS(Line l, Line s) {
if (intersectLS(l, s)) return 0;
return min(distanceLP(l, s.p1), distanceLP(l, s.p2));
}
double distanceSP(Line s, Point p) {
Point r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s.p1 - p), abs(s.p2 - p));
}
double distanceSS(Line s, Line t) {
if (intersectSS(s, t)) return 0;
return min(min(distanceSP(s, t.p1), distanceSP(s, t.p2)),
min(distanceSP(t, s.p1), distanceSP(t, s.p2)));
}
Point crosspoint(Line l, Line m) {
double A = cross(l.p2 - l.p1, m.p2 - m.p1);
double B = cross(l.p2 - l.p1, l.p2 - m.p1);
if (abs(A) < EPS && abs(B) < EPS) return m.p1; // same line
if (abs(A) < EPS) assert(false); // !!!PRECONDITION NOT SATISFIED!!!
return m.p1 + (m.p2 - m.p1) * (B / A);
}
struct Edge
{
int from,to;
double cost;
Edge(int from=inf,int to=inf,double cost=inf):from(from),to(to),cost(cost){}
bool operator < (const Edge& a)const
{
return cost < a.cost;
}
};
typedef vector<Edge> vE;
typedef vector<vE> vvE;
Point star,dest;
vector<vector<Edge> > segmentArrangement(vector<Segment> vs,vector<Point> &ps)
{
/*
端点もいれたいなら
ここであらかじめ端点だけpsにいれる
*/
rep(i,vs.size())
REP(j,i+1,vs.size())
if(intersectSS(vs[i],vs[j]))
ps.push_back(Point(crosspoint(vs[i],vs[j])));
//
ps.push_back(star);
ps.push_back(dest);
//
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
vector<vector<Edge> > ret(ps.size());
for(int i=0;i<vs.size();i++)
{
vector<pair<double,int> > list;
rep(j,ps.size())
if(intersectSP(vs[i],ps[j]))
list.push_back(pair<double,int>(norm(vs[i].p1-ps[j]),j));
sort(list.begin(),list.end());
//for(int j=0;j<list.size()-1;++j) is not good
for(int j=0;j+1<list.size();++j)
{
int from = list[j].second, to = list[j+1].second;
double cost = abs(ps[from]-ps[to]);
ret[from].push_back(Edge(from,to,cost));
ret[to].push_back(Edge(to,from,cost));
}
}
return ret;
}
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
struct Pox
{
int prev,cur;
double cost;
Pox(int prev=inf,int cur=inf,double cost=inf):prev(prev),cur(cur),cost(cost){}
bool operator < (const Pox& a)const
{
return cost > a.cost;
}
};
int n;
double calcCost(Point A,Point B,Point C)
{
double a = sqrt(pow2(B.x-C.x)+pow2(B.y-C.y));
double b = sqrt(pow2(A.x-C.x)+pow2(A.y-C.y));
double c = sqrt(pow2(A.x-B.x)+pow2(A.y-B.y));
//cout << a << ",x," << b << ",x," << c << endl;
return acos((c*c+a*a-b*b)/(2.0*c*a))*180/M_PI;
}
void dijkstra(vvE &G,vector<Point> &ps)
{
int sp,ep;
sp = ep = inf;
rep(i,ps.size())
if(ps[i] == star)sp = i;
else if(ps[i] == dest)ep = i;
//cout << "sp = " << sp << " ep = " << ep << endl;
assert(sp != inf);
assert(ep != inf);
int N = ps.size();
double mincost[N][N];
rep(i,N)rep(j,N)mincost[i][j] = (i==j?0:inf);
priority_queue<Pox> Q;
Q.push(Pox(sp,sp,0));
//cout << "dijkstra----" << endl;
while(!Q.empty())
{
Pox pox = Q.top(); Q.pop();
//cout << "(" << pox.prev << "," << pox.cur << "," << pox.cost << ")" << endl;
if(pox.cur == ep)
{
printf("%.12lf\n",pox.cost);
//cout << setiosflags(ios::fixed) << setprecision(10) << pox.cost << endl;
return;
}
int prev = pox.prev;
int cur = pox.cur;
double cost = pox.cost;
rep(i,G[cur].size())
{
int next = G[cur][i].to;
if(prev == next)continue;
Point e = ps[prev] - ps[cur];
e = e/abs(e);
e = e*1000;
double arg = 180 - calcCost(ps[prev],ps[cur],ps[next]);
//cout << "arg = " << arg << endl;
if(intersectSP(Segment(ps[prev]-e,ps[cur]+e),ps[next]))arg = 0;
double ncost = cost + arg;
if(prev == cur)ncost = 0;
//cout << "from " << cur << " to " << next << " the cost = " << ncost << endl;
if(!equals(ncost,mincost[cur][next]) && mincost[cur][next] > ncost)
{
mincost[cur][next] = ncost;
Q.push(Pox(cur,next,ncost));
}
}
}
cout << -1 << endl;
}
void compute(vector<Segment>& vec)
{
vector<Point> ps;
vvE G = segmentArrangement(vec,ps);
/*
cout << "ps--------" << endl;
rep(i,ps.size())cout << "ps[" << i << "] = " << ps[i] << endl;
cout << endl;
cout << "G---------" << endl;
rep(i,G.size())
{
rep(j,G[i].size())
{
cout << "(" << G[i][j].from << "," << G[i][j].to << ") ";
}
cout << endl;
}
cout << endl;
*/
dijkstra(G,ps);
}
int main()
{
while(cin >> n,n)
{
vector<Segment> vec(n);
rep(i,n)
{
cin >> vec[i].p1.x >> vec[i].p1.y >> vec[i].p2.x >> vec[i].p2.y;
//vec[i].p1 = vec[i].p1 + 1000;
//vec[i].p2 = vec[i].p2 + 1000;
}
merge_segments(vec);
cin >> star.x >> star.y >> dest.x >> dest.y;
compute(vec);
}
return 0;
}
``` |
#include<bits/stdc++.h>
using namespace std;
const double EPS = 1e-8, PI = acos(-1), INF = 1e9;
inline bool eq(double a, double b)
{
return abs(b - a) < EPS;
}
struct Point
{
double x, y;
Point() {};
Point(double x, double y) : x(x), y(y) {};
Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
Point operator*(const double b) const { return Point(x * b, y * b); }
Point operator*(const Point &b) const { return Point(x * b.x - y * b.y, x * b.y + y * b.x); }
Point operator/(const double b) const { return Point(x / b, y / b); }
bool operator<(const Point &b) const { return x != b.x ? x < b.x : y < b.y; }
bool operator==(const Point &b) const { return eq(x, b.x) && eq(y, b.y); }
double norm() { return x * x + y * y; }
double arg() { return atan2(x, y); }
double abs() { return sqrt(norm()); }
Point rotate(double theta) { return Point(cos(theta) * x - sin(theta) * y, sin(theta) * x + cos(theta) * y); }
Point rotate90() { return Point(-y, x); }
friend ostream &operator<<(ostream &os, Point &p) { return os << "(" << p.x << "," << p.y << ")"; }
friend istream &operator>>(istream &is, Point &a) { return is >> a.x >> a.y; }
};
double cross(const Point &a, const Point &b)
{
return a.x * b.y - a.y * b.x;
}
double dot(const Point &a, const Point &b)
{
return a.x * b.x + a.y * b.y;
}
int ccw(const Point &a, Point b, Point c)
{
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1;
if(cross(b, c) < -EPS) return -1;
if(dot(b, c) < 0) return +2;
if(b.norm() < c.norm()) return -2;
return 0;
}
struct Segment
{
Point a, b;
Segment() {};
Segment(Point a, Point b) : a(a), b(b) {};
friend ostream &operator<<(ostream &os, Segment &p) { return os << "(" << p.a.x << "," << p.a.y << ") to (" << p.b.x << "," << p.b.y << ")"; }
friend istream &operator>>(istream &is, Segment &a) { return is >> a.a.x >> a.a.y >> a.b.x >> a.b.y; }
};
bool Intersect(const Segment &s, const Point &p)
{
return ccw(s.a, s.b, p) == 0;
}
bool Intersect(const Segment &s, const Segment &t)
{
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&
ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
Point Crosspoint(const Segment &l, const Segment &m)
{
double A = cross(l.b - l.a, m.b - m.a);
double B = cross(l.b - l.a, l.b - m.a);
if(abs(A) < EPS && abs(B) < EPS) return m.a; // same line
return m.a + (m.b - m.a) * B / A;
}
vector< vector< int > > SegmentArrangement(vector< Segment > &segs, vector< Point > &ps)
{
vector< vector< int > > g;
ps.clear();
const int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(Intersect(segs[i], segs[j])) {
ps.emplace_back(Crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
const int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(Intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
double GetAngle(const Point &a, const Point &b, const Point &c)
{
const Point v = b - a, w = c - b;
double alpha = atan2(v.y, v.x), beta = atan2(w.y, w.x);
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180.0 / PI;
return min(theta, 360.0 - theta);
}
double Dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps)
{
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< double > > min_cost(g.size(), vector< double >(g.size(), INF));
typedef tuple< double, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
double cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + GetAngle(ps[pre], ps[cur], ps[to]);
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main()
{
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
auto g = SegmentArrangement(segs, ps);
double ret = Dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
} | ### Prompt
Construct a Cpp code solution to the problem outlined:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include<bits/stdc++.h>
using namespace std;
const double EPS = 1e-8, PI = acos(-1), INF = 1e9;
inline bool eq(double a, double b)
{
return abs(b - a) < EPS;
}
struct Point
{
double x, y;
Point() {};
Point(double x, double y) : x(x), y(y) {};
Point operator+(const Point &b) const { return Point(x + b.x, y + b.y); }
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
Point operator*(const double b) const { return Point(x * b, y * b); }
Point operator*(const Point &b) const { return Point(x * b.x - y * b.y, x * b.y + y * b.x); }
Point operator/(const double b) const { return Point(x / b, y / b); }
bool operator<(const Point &b) const { return x != b.x ? x < b.x : y < b.y; }
bool operator==(const Point &b) const { return eq(x, b.x) && eq(y, b.y); }
double norm() { return x * x + y * y; }
double arg() { return atan2(x, y); }
double abs() { return sqrt(norm()); }
Point rotate(double theta) { return Point(cos(theta) * x - sin(theta) * y, sin(theta) * x + cos(theta) * y); }
Point rotate90() { return Point(-y, x); }
friend ostream &operator<<(ostream &os, Point &p) { return os << "(" << p.x << "," << p.y << ")"; }
friend istream &operator>>(istream &is, Point &a) { return is >> a.x >> a.y; }
};
double cross(const Point &a, const Point &b)
{
return a.x * b.y - a.y * b.x;
}
double dot(const Point &a, const Point &b)
{
return a.x * b.x + a.y * b.y;
}
int ccw(const Point &a, Point b, Point c)
{
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1;
if(cross(b, c) < -EPS) return -1;
if(dot(b, c) < 0) return +2;
if(b.norm() < c.norm()) return -2;
return 0;
}
struct Segment
{
Point a, b;
Segment() {};
Segment(Point a, Point b) : a(a), b(b) {};
friend ostream &operator<<(ostream &os, Segment &p) { return os << "(" << p.a.x << "," << p.a.y << ") to (" << p.b.x << "," << p.b.y << ")"; }
friend istream &operator>>(istream &is, Segment &a) { return is >> a.a.x >> a.a.y >> a.b.x >> a.b.y; }
};
bool Intersect(const Segment &s, const Point &p)
{
return ccw(s.a, s.b, p) == 0;
}
bool Intersect(const Segment &s, const Segment &t)
{
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&
ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
Point Crosspoint(const Segment &l, const Segment &m)
{
double A = cross(l.b - l.a, m.b - m.a);
double B = cross(l.b - l.a, l.b - m.a);
if(abs(A) < EPS && abs(B) < EPS) return m.a; // same line
return m.a + (m.b - m.a) * B / A;
}
vector< vector< int > > SegmentArrangement(vector< Segment > &segs, vector< Point > &ps)
{
vector< vector< int > > g;
ps.clear();
const int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(Intersect(segs[i], segs[j])) {
ps.emplace_back(Crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
const int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(Intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
double GetAngle(const Point &a, const Point &b, const Point &c)
{
const Point v = b - a, w = c - b;
double alpha = atan2(v.y, v.x), beta = atan2(w.y, w.x);
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180.0 / PI;
return min(theta, 360.0 - theta);
}
double Dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps)
{
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< double > > min_cost(g.size(), vector< double >(g.size(), INF));
typedef tuple< double, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
double cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + GetAngle(ps[pre], ps[cur], ps[to]);
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main()
{
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
auto g = SegmentArrangement(segs, ps);
double ret = Dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
}
``` |
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cassert>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <complex>
#include <stack>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <bitset>
#include <functional>
#include <iterator>
using namespace std;
#define dump(n) cout<<"# "<<#n<<'='<<(n)<<endl
#define repi(i,a,b) for(int i=int(a);i<int(b);i++)
#define peri(i,a,b) for(int i=int(b);i-->int(a);)
#define rep(i,n) repi(i,0,n)
#define per(i,n) peri(i,0,n)
#define iter(c) __typeof__((c).begin())
#define foreach(i,c) for(iter(c) i=(c).begin();i!=(c).end();++i)
#define all(c) (c).begin(),(c).end()
#define mp make_pair
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int,int> pii;
const int INFTY=1<<29;
const double EPS=1e-9;
template<typename T1,typename T2>
ostream& operator<<(ostream& os,const pair<T1,T2>& p){
return os<<'('<<p.first<<','<<p.second<<')';
}
template<typename T>
ostream& operator<<(ostream& os,const vector<T>& a){
os<<'[';
rep(i,a.size()) os<<(i?" ":"")<<a[i];
return os<<']';
}
const double PI=acos(-1);
struct Point{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
};
struct Line{
Point pos,dir;
Line(){}
Line(Point p,Point d):pos(p),dir(d){}
Line(double px,double py,double dx,double dy):pos(px,py),dir(dx,dy){}
};
typedef Line Segment;
bool operator==(Point a,Point b){
return abs(a.x-b.x)<EPS && abs(a.y-b.y)<EPS;
}
bool operator!=(Point a,Point b){
return !(a==b);
}
Point operator+(Point a,Point b){
return Point(a.x+b.x,a.y+b.y);
}
Point operator-(Point a,Point b){
return Point(a.x-b.x,a.y-b.y);
}
Point operator*(double c,Point p){
return Point(c*p.x,c*p.y);
}
Point operator/(Point p,double c){
return Point(p.x/c,p.y/c);
}
struct LessX{
bool operator()(Point a,Point b){
return abs(a.x-b.x)>EPS?a.x<b.x-EPS:a.y<b.y-EPS;
}
};
int Signum(double x){
return x<-EPS?-1:x<EPS?0:1;
}
double Abs(Point p){
return sqrt(p.x*p.x+p.y*p.y);
}
double Abs2(Point p){
return p.x*p.x+p.y*p.y;
}
double Arg(Point p){
return atan2(p.y,p.x);
}
double Dot(Point a,Point b){
return a.x*b.x+a.y*b.y;
}
double Cross(Point a,Point b){
return a.x*b.y-a.y*b.x;
}
int CCW(Point a,Point b,Point c){
Point d1=b-a,d2=c-a;
if(int sign=Signum(Cross(d1,d2)))
return sign; // 1:ccw,-1:cw
if(Dot(d1,d2)<-EPS)
return -2; // c-a-b
if(Abs2(d1)<Abs2(d2)-EPS)
return 2; // a-b-c
return 0; // a-c-b
}
bool IntersectSP(Segment s,Point p){
return CCW(s.pos,s.pos+s.dir,p)==0;
}
bool IntersectSS(Segment a,Segment b){
int c1=CCW(a.pos,a.pos+a.dir,b.pos),c2=CCW(a.pos,a.pos+a.dir,b.pos+b.dir);
int c3=CCW(b.pos,b.pos+b.dir,a.pos),c4=CCW(b.pos,b.pos+b.dir,a.pos+a.dir);
return c1*c2<=0 && c3*c4<=0;
}
Point InterPointLL(Line a,Line b){
if(abs(Cross(a.dir,b.dir))<EPS)
return a.pos;
return a.pos+Cross(b.pos-a.pos,b.dir)/Cross(a.dir,b.dir)*a.dir;
}
Point InterPointSS(Segment a,Segment b){
if(abs(Cross(a.dir,b.dir))<EPS){
if(IntersectSP(b,a.pos)) return a.pos;
if(IntersectSP(b,a.pos+a.dir)) return a.pos+a.dir;
if(IntersectSP(a,b.pos)) return b.pos;
if(IntersectSP(a,b.pos+b.dir)) return b.pos+b.dir;
}
return InterPointLL(a,b);
}
struct Edge{
int src,dst;
double weight;
Edge(){}
Edge(int s,int d,double w):src(s),dst(d),weight(w){}
bool operator<(const Edge& e)const{return Signum(weight-e.weight)<0;}
bool operator>(const Edge& e)const{return Signum(weight-e.weight)>0;}
};
typedef vector<vector<Edge> > Graph;
void SegmentArrangement(const vector<Segment>& ss,Graph& g,vector<Point>& ps){
rep(i,ss.size()){
ps.push_back(ss[i].pos);
ps.push_back(ss[i].pos+ss[i].dir);
repi(j,i+1,ss.size()) if(IntersectSS(ss[i],ss[j]))
ps.push_back(InterPointSS(ss[i],ss[j]));
}
sort(all(ps),LessX());
ps.erase(unique(all(ps)),ps.end());
g.resize(ps.size());
rep(i,ss.size()){
vector<pair<double,int> > ds;
rep(j,ps.size()) if(IntersectSP(ss[i],ps[j]))
ds.push_back(mp(Abs(ps[j]-ss[i].pos),j));
sort(all(ds));
rep(j,ds.size()-1){
int u=ds[j].second,v=ds[j+1].second;
double w=ds[j+1].first-ds[j].first;
g[u].push_back(Edge(u,v,w));
g[v].push_back(Edge(v,u,w));
}
}
}
int main()
{
for(int n;cin>>n,n;){
vector<Segment> ss(n);
rep(i,n){
int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2;
ss[i]=Segment(x1,y1,x2-x1,y2-y1);
}
Point st,go;
cin>>st.x>>st.y>>go.x>>go.y;
Graph g;
vector<Point> ps;
SegmentArrangement(ss,g,ps);
vi sum(g.size());
repi(i,1,g.size())
sum[i]=sum[i-1]+g[i-1].size();
Graph g2(sum.back()+g.back().size());
rep(i,g.size()) rep(j,g[i].size()) rep(k,g[g[i][j].dst].size()){
Edge e1=g[i][j],e2=g[g[i][j].dst][k];
int u=sum[e1.src]+j,v=sum[e2.src]+k;
double w=abs(Arg(ps[e1.dst]-ps[e1.src])-Arg(ps[e2.dst]-ps[e2.src]))*180/PI;
w=min(w,360-w);
g2[u].emplace_back(u,v,w);
}
vi sts,gos;
rep(i,g.size()) rep(j,g[i].size()){
Segment seg(ps[i],ps[g[i][j].dst]-ps[i]);
if(IntersectSP(seg,st)) sts.push_back(sum[i]+j);
if(IntersectSP(seg,go)) gos.push_back(sum[i]+j);
}
vd ws(g2.size(),INFTY);
priority_queue<Edge,vector<Edge>,greater<Edge>> pq;
rep(i,sts.size()) pq.emplace(-1,sts[i],0);
while(!pq.empty()){
Edge cur=pq.top(); pq.pop();
if(ws[cur.dst]!=INFTY) continue;
ws[cur.dst]=cur.weight;
for(Edge e:g2[cur.dst])
pq.emplace(e.src,e.dst,cur.weight+e.weight);
}
double res=INFTY;
rep(i,gos.size()) res=min(res,ws[gos[i]]);
if(res==INFTY) puts("-1");
else printf("%f\n",res);
}
return 0;
} | ### Prompt
Create a solution in cpp for the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cassert>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <complex>
#include <stack>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <bitset>
#include <functional>
#include <iterator>
using namespace std;
#define dump(n) cout<<"# "<<#n<<'='<<(n)<<endl
#define repi(i,a,b) for(int i=int(a);i<int(b);i++)
#define peri(i,a,b) for(int i=int(b);i-->int(a);)
#define rep(i,n) repi(i,0,n)
#define per(i,n) peri(i,0,n)
#define iter(c) __typeof__((c).begin())
#define foreach(i,c) for(iter(c) i=(c).begin();i!=(c).end();++i)
#define all(c) (c).begin(),(c).end()
#define mp make_pair
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int,int> pii;
const int INFTY=1<<29;
const double EPS=1e-9;
template<typename T1,typename T2>
ostream& operator<<(ostream& os,const pair<T1,T2>& p){
return os<<'('<<p.first<<','<<p.second<<')';
}
template<typename T>
ostream& operator<<(ostream& os,const vector<T>& a){
os<<'[';
rep(i,a.size()) os<<(i?" ":"")<<a[i];
return os<<']';
}
const double PI=acos(-1);
struct Point{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
};
struct Line{
Point pos,dir;
Line(){}
Line(Point p,Point d):pos(p),dir(d){}
Line(double px,double py,double dx,double dy):pos(px,py),dir(dx,dy){}
};
typedef Line Segment;
bool operator==(Point a,Point b){
return abs(a.x-b.x)<EPS && abs(a.y-b.y)<EPS;
}
bool operator!=(Point a,Point b){
return !(a==b);
}
Point operator+(Point a,Point b){
return Point(a.x+b.x,a.y+b.y);
}
Point operator-(Point a,Point b){
return Point(a.x-b.x,a.y-b.y);
}
Point operator*(double c,Point p){
return Point(c*p.x,c*p.y);
}
Point operator/(Point p,double c){
return Point(p.x/c,p.y/c);
}
struct LessX{
bool operator()(Point a,Point b){
return abs(a.x-b.x)>EPS?a.x<b.x-EPS:a.y<b.y-EPS;
}
};
int Signum(double x){
return x<-EPS?-1:x<EPS?0:1;
}
double Abs(Point p){
return sqrt(p.x*p.x+p.y*p.y);
}
double Abs2(Point p){
return p.x*p.x+p.y*p.y;
}
double Arg(Point p){
return atan2(p.y,p.x);
}
double Dot(Point a,Point b){
return a.x*b.x+a.y*b.y;
}
double Cross(Point a,Point b){
return a.x*b.y-a.y*b.x;
}
int CCW(Point a,Point b,Point c){
Point d1=b-a,d2=c-a;
if(int sign=Signum(Cross(d1,d2)))
return sign; // 1:ccw,-1:cw
if(Dot(d1,d2)<-EPS)
return -2; // c-a-b
if(Abs2(d1)<Abs2(d2)-EPS)
return 2; // a-b-c
return 0; // a-c-b
}
bool IntersectSP(Segment s,Point p){
return CCW(s.pos,s.pos+s.dir,p)==0;
}
bool IntersectSS(Segment a,Segment b){
int c1=CCW(a.pos,a.pos+a.dir,b.pos),c2=CCW(a.pos,a.pos+a.dir,b.pos+b.dir);
int c3=CCW(b.pos,b.pos+b.dir,a.pos),c4=CCW(b.pos,b.pos+b.dir,a.pos+a.dir);
return c1*c2<=0 && c3*c4<=0;
}
Point InterPointLL(Line a,Line b){
if(abs(Cross(a.dir,b.dir))<EPS)
return a.pos;
return a.pos+Cross(b.pos-a.pos,b.dir)/Cross(a.dir,b.dir)*a.dir;
}
Point InterPointSS(Segment a,Segment b){
if(abs(Cross(a.dir,b.dir))<EPS){
if(IntersectSP(b,a.pos)) return a.pos;
if(IntersectSP(b,a.pos+a.dir)) return a.pos+a.dir;
if(IntersectSP(a,b.pos)) return b.pos;
if(IntersectSP(a,b.pos+b.dir)) return b.pos+b.dir;
}
return InterPointLL(a,b);
}
struct Edge{
int src,dst;
double weight;
Edge(){}
Edge(int s,int d,double w):src(s),dst(d),weight(w){}
bool operator<(const Edge& e)const{return Signum(weight-e.weight)<0;}
bool operator>(const Edge& e)const{return Signum(weight-e.weight)>0;}
};
typedef vector<vector<Edge> > Graph;
void SegmentArrangement(const vector<Segment>& ss,Graph& g,vector<Point>& ps){
rep(i,ss.size()){
ps.push_back(ss[i].pos);
ps.push_back(ss[i].pos+ss[i].dir);
repi(j,i+1,ss.size()) if(IntersectSS(ss[i],ss[j]))
ps.push_back(InterPointSS(ss[i],ss[j]));
}
sort(all(ps),LessX());
ps.erase(unique(all(ps)),ps.end());
g.resize(ps.size());
rep(i,ss.size()){
vector<pair<double,int> > ds;
rep(j,ps.size()) if(IntersectSP(ss[i],ps[j]))
ds.push_back(mp(Abs(ps[j]-ss[i].pos),j));
sort(all(ds));
rep(j,ds.size()-1){
int u=ds[j].second,v=ds[j+1].second;
double w=ds[j+1].first-ds[j].first;
g[u].push_back(Edge(u,v,w));
g[v].push_back(Edge(v,u,w));
}
}
}
int main()
{
for(int n;cin>>n,n;){
vector<Segment> ss(n);
rep(i,n){
int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2;
ss[i]=Segment(x1,y1,x2-x1,y2-y1);
}
Point st,go;
cin>>st.x>>st.y>>go.x>>go.y;
Graph g;
vector<Point> ps;
SegmentArrangement(ss,g,ps);
vi sum(g.size());
repi(i,1,g.size())
sum[i]=sum[i-1]+g[i-1].size();
Graph g2(sum.back()+g.back().size());
rep(i,g.size()) rep(j,g[i].size()) rep(k,g[g[i][j].dst].size()){
Edge e1=g[i][j],e2=g[g[i][j].dst][k];
int u=sum[e1.src]+j,v=sum[e2.src]+k;
double w=abs(Arg(ps[e1.dst]-ps[e1.src])-Arg(ps[e2.dst]-ps[e2.src]))*180/PI;
w=min(w,360-w);
g2[u].emplace_back(u,v,w);
}
vi sts,gos;
rep(i,g.size()) rep(j,g[i].size()){
Segment seg(ps[i],ps[g[i][j].dst]-ps[i]);
if(IntersectSP(seg,st)) sts.push_back(sum[i]+j);
if(IntersectSP(seg,go)) gos.push_back(sum[i]+j);
}
vd ws(g2.size(),INFTY);
priority_queue<Edge,vector<Edge>,greater<Edge>> pq;
rep(i,sts.size()) pq.emplace(-1,sts[i],0);
while(!pq.empty()){
Edge cur=pq.top(); pq.pop();
if(ws[cur.dst]!=INFTY) continue;
ws[cur.dst]=cur.weight;
for(Edge e:g2[cur.dst])
pq.emplace(e.src,e.dst,cur.weight+e.weight);
}
double res=INFTY;
rep(i,gos.size()) res=min(res,ws[gos[i]]);
if(res==INFTY) puts("-1");
else printf("%f\n",res);
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
using Real = double;
using Point = complex< Real >;
const Real EPS = 1e-8, PI = acos(-1);
inline bool eq(Real a, Real b) { return fabs(b - a) < EPS; }
Point operator*(const Point &p, const Real &d) {
return Point(real(p) * d, imag(p) * d);
}
istream &operator>>(istream &is, Point &p) {
Real a, b;
is >> a >> b;
p = Point(a, b);
return is;
}
ostream &operator<<(ostream &os, Point &p) {
os << fixed << setprecision(10) << p.real() << " " << p.imag();
}
Point rotate(Real theta, const Point &p) {
return Point(cos(theta) * p.real() - sin(theta) * p.imag(), sin(theta) * p.real() + cos(theta) * p.imag());
}
Real radian_to_degree(Real r) {
return (r * 180.0 / PI);
}
Real degree_to_radian(Real d) {
return (d * PI / 180.0);
}
Real get_angle(const Point &a, const Point &b, const Point &c) {
const Point v(b - a), w(c - b);
Real alpha = atan2(v.imag(), v.real()), beta = atan2(w.imag(), w.real());
if(alpha > beta) swap(alpha, beta);
Real theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
namespace std {
bool operator<(const Point &a, const Point &b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
}
struct Line {
Point a, b;
Line() = default;
Line(Point a, Point b) : a(a), b(b) {}
Line(Real A, Real B, Real C) // Ax + By = C
{
if(eq(A, 0)) a = Point(0, C / B), b = Point(1, C / B);
else if(eq(B, 0)) b = Point(C / A, 0), b = Point(C / A, 1);
else a = Point(0, C / B), b = Point(C / A, 0);
}
friend ostream &operator<<(ostream &os, Line &p) {
return os << p.a << " to " << p.b;
}
friend istream &operator>>(istream &is, Line &a) {
return is >> a.a >> a.b;
}
};
struct Segment : Line {
Segment() = default;
Segment(Point a, Point b) : Line(a, b) {}
};
struct Circle {
Point p;
Real r;
Circle() = default;
Circle(Point p, Real r) : p(p), r(r) {}
};
using Points = vector< Point >;
using Polygon = vector< Point >;
using Segments = vector< Segment >;
using Lines = vector< Line >;
using Circles = vector< Circle >;
Real cross(const Point &a, const Point &b) {
return real(a) * imag(b) - imag(a) * real(b);
}
Real dot(const Point &a, const Point &b) {
return real(a) * real(b) + imag(a) * imag(b);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C
int ccw(const Point &a, Point b, Point c) {
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1; // "COUNTER_CLOCKWISE"
if(cross(b, c) < -EPS) return -1; // "CLOCKWISE"
if(dot(b, c) < 0) return +2; // "ONLINE_BACK"
if(norm(b) < norm(c)) return -2; // "ONLINE_FRONT"
return 0; // "ON_SEGMENT"
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool parallel(const Line &a, const Line &b) {
return eq(cross(a.b - a.a, b.b - b.a), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool orthogonal(const Line &a, const Line &b) {
return eq(dot(a.a - a.b, b.a - b.b), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A
Point projection(const Line &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
Point projection(const Segment &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B
Point reflection(const Line &l, const Point &p) {
return p + (projection(l, p) - p) * 2.0;
}
bool intersect(const Line &l, const Point &p) {
return abs(ccw(l.a, l.b, p)) != 1;
}
bool intersect(const Line &l, const Line &m) {
return abs(cross(l.b - l.a, m.b - m.a)) > EPS || abs(cross(l.b - l.a, m.b - l.a)) < EPS;
}
bool intersect(const Segment &s, const Point &p) {
return ccw(s.a, s.b, p) == 0;
}
bool intersect(const Line &l, const Segment &s) {
return cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < EPS;
}
Real distance(const Line &l, const Point &p);
bool intersect(const Circle &c, const Line &l) {
return distance(l, c.p) <= c.r + EPS;
}
bool intersect(const Circle &c, const Point &p) {
return abs(abs(p - c.p) - c.r) < EPS;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B
bool intersect(const Segment &s, const Segment &t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 && ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
int intersect(const Circle &c, const Segment &l) {
if(norm(projection(l, c.p) - c.p) - c.r * c.r > EPS) return 0;
auto d1 = abs(c.p - l.a), d2 = abs(c.p - l.b);
if(d1 < c.r + EPS && d2 < c.r + EPS) return 0;
if(d1 < c.r - EPS && d2 > c.r + EPS || d1 > c.r + EPS && d2 < c.r - EPS) return 1;
const Point h = projection(l, c.p);
if(dot(l.a - h, l.b - h) < 0) return 2;
return 0;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=jp
int intersect(Circle c1, Circle c2) {
if(c1.r < c2.r) swap(c1, c2);
Real d = abs(c1.p - c2.p);
if(c1.r + c2.r < d) return 4;
if(eq(c1.r + c2.r, d)) return 3;
if(c1.r - c2.r < d) return 2;
if(eq(c1.r - c2.r, d)) return 1;
return 0;
}
Real distance(const Point &a, const Point &b) {
return abs(a - b);
}
Real distance(const Line &l, const Point &p) {
return abs(p - projection(l, p));
}
Real distance(const Line &l, const Line &m) {
return intersect(l, m) ? 0 : distance(l, m.a);
}
Real distance(const Segment &s, const Point &p) {
Point r = projection(s, p);
if(intersect(s, r)) return abs(r - p);
return min(abs(s.a - p), abs(s.b - p));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D
Real distance(const Segment &a, const Segment &b) {
if(intersect(a, b)) return 0;
return min({distance(a, b.a), distance(a, b.b), distance(b, a.a), distance(b, a.b)});
}
Real distance(const Line &l, const Segment &s) {
if(intersect(l, s)) return 0;
return min(distance(l, s.a), distance(l, s.b));
}
Point crosspoint(const Line &l, const Line &m) {
Real A = cross(l.b - l.a, m.b - m.a);
Real B = cross(l.b - l.a, l.b - m.a);
if(eq(abs(A), 0.0) && eq(abs(B), 0.0)) return m.a;
return m.a + (m.b - m.a) * B / A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C
Point crosspoint(const Segment &l, const Segment &m) {
return crosspoint(Line(l), Line(m));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D
pair< Point, Point > crosspoint(const Circle &c, const Line l) {
Point pr = projection(l, c.p);
Point e = (l.b - l.a) / abs(l.b - l.a);
if(eq(distance(l, c.p), c.r)) return {pr, pr};
double base = sqrt(c.r * c.r - norm(pr - c.p));
return {pr - e * base, pr + e * base};
}
pair< Point, Point > crosspoint(const Circle &c, const Segment &l) {
Line aa = Line(l.a, l.b);
if(intersect(c, l) == 2) return crosspoint(c, aa);
auto ret = crosspoint(c, aa);
if(dot(l.a - ret.first, l.b - ret.first) < 0) ret.second = ret.first;
else ret.first = ret.second;
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E
pair< Point, Point > crosspoint(const Circle &c1, const Circle &c2) {
Real d = abs(c1.p - c2.p);
Real a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));
Real t = atan2(c2.p.imag() - c1.p.imag(), c2.p.real() - c1.p.real());
Point p1 = c1.p + Point(cos(t + a) * c1.r, sin(t + a) * c1.r);
Point p2 = c1.p + Point(cos(t - a) * c1.r, sin(t - a) * c1.r);
return {p1, p2};
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_F
pair< Point, Point > tangent(const Circle &c1, const Point &p2) {
return crosspoint(c1, Circle(p2, sqrt(norm(c1.p - p2) - c1.r * c1.r)));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_G
Lines tangent(Circle c1, Circle c2) {
Lines ret;
if(c1.r < c2.r) swap(c1, c2);
Real g = norm(c1.p - c2.p);
if(eq(g, 0)) return ret;
Point u = (c2.p - c1.p) / sqrt(g);
Point v = rotate(PI * 0.5, u);
for(int s : {-1, 1}) {
Real h = (c1.r + s * c2.r) / sqrt(g);
if(eq(1 - h * h, 0)) {
ret.emplace_back(c1.p + u * c1.r, c1.p + (u + v) * c1.r);
} else if(1 - h * h > 0) {
Point uu = u * h, vv = v * sqrt(1 - h * h);
ret.emplace_back(c1.p + (uu + vv) * c1.r, c2.p - (uu + vv) * c2.r * s);
ret.emplace_back(c1.p + (uu - vv) * c1.r, c2.p - (uu - vv) * c2.r * s);
}
}
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B
bool is_convex(const Polygon &p) {
int n = (int) p.size();
for(int i = 0; i < n; i++) {
if(ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == -1) return false;
}
return true;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A
Polygon convex_hull(Polygon &p) {
int n = (int) p.size(), k = 0;
if(n <= 2) return p;
sort(p.begin(), p.end());
vector< Point > ch(2 * n);
for(int i = 0; i < n; ch[k++] = p[i++]) {
while(k >= 2 && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {
while(k >= t && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
ch.resize(k - 1);
return ch;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C
enum {
OUT, ON, IN
};
int contains(const Polygon &Q, const Point &p) {
bool in = false;
for(int i = 0; i < Q.size(); i++) {
Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;
if(a.imag() > b.imag()) swap(a, b);
if(a.imag() <= 0 && 0 < b.imag() && cross(a, b) < 0) in = !in;
if(cross(a, b) == 0 && dot(a, b) <= 0) return ON;
}
return in ? IN : OUT;
}
bool merge_if_able(Segment &s1, const Segment &s2) {
if(abs(cross(s1.b - s1.a, s2.b - s2.a)) > EPS) return false;
if(ccw(s1.a, s2.a, s1.b) == 1 || ccw(s1.a, s2.a, s1.b) == -1) return false;
if(ccw(s1.a, s1.b, s2.a) == -2 || ccw(s2.a, s2.b, s1.a) == -2) return false;
s1 = Segment(min(s1.a, s2.a), max(s1.b, s2.b));
return true;
}
void merge_segments(vector< Segment > &segs) {
for(int i = 0; i < segs.size(); i++) {
if(segs[i].b < segs[i].a) swap(segs[i].a, segs[i].b);
}
for(int i = 0; i < segs.size(); i++) {
for(int j = i + 1; j < segs.size(); j++) {
if(merge_if_able(segs[i], segs[j])) {
segs[j--] = segs.back(), segs.pop_back();
}
}
}
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1033
vector< vector< int > > segment_arrangement(vector< Segment > &segs, vector< Point > &ps) {
vector< vector< int > > g;
int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(intersect(segs[i], segs[j])) {
ps.emplace_back(crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C
Polygon convex_cut(const Polygon &U, Line l) {
Polygon ret;
for(int i = 0; i < U.size(); i++) {
Point now = U[i], nxt = U[(i + 1) % U.size()];
if(ccw(l.a, l.b, now) != -1) ret.push_back(now);
if(ccw(l.a, l.b, now) * ccw(l.a, l.b, nxt) < 0) {
ret.push_back(crosspoint(Line(now, nxt), l));
}
}
return (ret);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A
Real area2(const Polygon &p) {
Real A = 0;
for(int i = 0; i < p.size(); ++i) {
A += cross(p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_H
Real area2(const Polygon &p, const Circle &c) {
if(p.size() < 3) return 0.0;
function< Real(Circle, Point, Point) > cross_area = [&](const Circle &c, const Point &a, const Point &b) {
Point va = c.p - a, vb = c.p - b;
Real f = cross(va, vb), ret = 0.0;
if(eq(f, 0.0)) return ret;
if(max(abs(va), abs(vb)) < c.r + EPS) return f;
if(distance(Segment(a, b), c.p) > c.r - EPS) return c.r * c.r * arg(vb * conj(va));
auto u = crosspoint(c, Segment(a, b));
vector< Point > tot{a, u.first, u.second, b};
for(int i = 0; i + 1 < tot.size(); i++) {
ret += cross_area(c, tot[i], tot[i + 1]);
}
return ret;
};
Real A = 0;
for(int i = 0; i < p.size(); i++) {
A += cross_area(c, p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B
Real convex_diameter(const Polygon &p) {
int N = (int) p.size();
int is = 0, js = 0;
for(int i = 1; i < N; i++) {
if(p[i].imag() > p[is].imag()) is = i;
if(p[i].imag() < p[js].imag()) js = i;
}
Real maxdis = norm(p[is] - p[js]);
int maxi, maxj, i, j;
i = maxi = is;
j = maxj = js;
do {
if(cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {
j = (j + 1) % N;
} else {
i = (i + 1) % N;
}
if(norm(p[i] - p[j]) > maxdis) {
maxdis = norm(p[i] - p[j]);
maxi = i;
maxj = j;
}
} while(i != is || j != js);
return sqrt(maxdis);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A
Real closest_pair(Points ps) {
if(ps.size() <= 1) throw (0);
sort(begin(ps), end(ps));
auto compare_y = [&](const Point &a, const Point &b) {
return imag(a) < imag(b);
};
vector< Point > beet(ps.size());
const Real INF = 1e18;
function< Real(int, int) > rec = [&](int left, int right) {
if(right - left <= 1) return INF;
int mid = (left + right) >> 1;
auto x = real(ps[mid]);
auto ret = min(rec(left, mid), rec(mid, right));
inplace_merge(begin(ps) + left, begin(ps) + mid, begin(ps) + right, compare_y);
int ptr = 0;
for(int i = left; i < right; i++) {
if(abs(real(ps[i]) - x) >= ret) continue;
for(int j = 0; j < ptr; j++) {
auto luz = ps[i] - beet[ptr - j - 1];
if(imag(luz) >= ret) break;
ret = min(ret, abs(luz));
}
beet[ptr++] = ps[i];
}
return ret;
};
return rec(0, (int) ps.size());
}
const Real INF = 1e18;
double GetAngle(const Point &a, const Point &b, const Point &c) {
const Point v = b - a, w = c - b;
double alpha = atan2(imag(v), real(v)), beta = atan2(imag(w), real(w));
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180.0 / PI;
return min(theta, 360.0 - theta);
}
Real dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps) {
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< Real > > min_cost(g.size(), vector< Real >(g.size(), INF));
typedef tuple< Real, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
Real cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + GetAngle(ps[pre], ps[cur], ps[to]);
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main() {
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
merge_segments(segs);
auto g = segment_arrangement(segs, ps);
double ret = dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
}
| ### Prompt
Develop a solution in cpp to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using Real = double;
using Point = complex< Real >;
const Real EPS = 1e-8, PI = acos(-1);
inline bool eq(Real a, Real b) { return fabs(b - a) < EPS; }
Point operator*(const Point &p, const Real &d) {
return Point(real(p) * d, imag(p) * d);
}
istream &operator>>(istream &is, Point &p) {
Real a, b;
is >> a >> b;
p = Point(a, b);
return is;
}
ostream &operator<<(ostream &os, Point &p) {
os << fixed << setprecision(10) << p.real() << " " << p.imag();
}
Point rotate(Real theta, const Point &p) {
return Point(cos(theta) * p.real() - sin(theta) * p.imag(), sin(theta) * p.real() + cos(theta) * p.imag());
}
Real radian_to_degree(Real r) {
return (r * 180.0 / PI);
}
Real degree_to_radian(Real d) {
return (d * PI / 180.0);
}
Real get_angle(const Point &a, const Point &b, const Point &c) {
const Point v(b - a), w(c - b);
Real alpha = atan2(v.imag(), v.real()), beta = atan2(w.imag(), w.real());
if(alpha > beta) swap(alpha, beta);
Real theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
namespace std {
bool operator<(const Point &a, const Point &b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
}
struct Line {
Point a, b;
Line() = default;
Line(Point a, Point b) : a(a), b(b) {}
Line(Real A, Real B, Real C) // Ax + By = C
{
if(eq(A, 0)) a = Point(0, C / B), b = Point(1, C / B);
else if(eq(B, 0)) b = Point(C / A, 0), b = Point(C / A, 1);
else a = Point(0, C / B), b = Point(C / A, 0);
}
friend ostream &operator<<(ostream &os, Line &p) {
return os << p.a << " to " << p.b;
}
friend istream &operator>>(istream &is, Line &a) {
return is >> a.a >> a.b;
}
};
struct Segment : Line {
Segment() = default;
Segment(Point a, Point b) : Line(a, b) {}
};
struct Circle {
Point p;
Real r;
Circle() = default;
Circle(Point p, Real r) : p(p), r(r) {}
};
using Points = vector< Point >;
using Polygon = vector< Point >;
using Segments = vector< Segment >;
using Lines = vector< Line >;
using Circles = vector< Circle >;
Real cross(const Point &a, const Point &b) {
return real(a) * imag(b) - imag(a) * real(b);
}
Real dot(const Point &a, const Point &b) {
return real(a) * real(b) + imag(a) * imag(b);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C
int ccw(const Point &a, Point b, Point c) {
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1; // "COUNTER_CLOCKWISE"
if(cross(b, c) < -EPS) return -1; // "CLOCKWISE"
if(dot(b, c) < 0) return +2; // "ONLINE_BACK"
if(norm(b) < norm(c)) return -2; // "ONLINE_FRONT"
return 0; // "ON_SEGMENT"
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool parallel(const Line &a, const Line &b) {
return eq(cross(a.b - a.a, b.b - b.a), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool orthogonal(const Line &a, const Line &b) {
return eq(dot(a.a - a.b, b.a - b.b), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A
Point projection(const Line &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
Point projection(const Segment &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B
Point reflection(const Line &l, const Point &p) {
return p + (projection(l, p) - p) * 2.0;
}
bool intersect(const Line &l, const Point &p) {
return abs(ccw(l.a, l.b, p)) != 1;
}
bool intersect(const Line &l, const Line &m) {
return abs(cross(l.b - l.a, m.b - m.a)) > EPS || abs(cross(l.b - l.a, m.b - l.a)) < EPS;
}
bool intersect(const Segment &s, const Point &p) {
return ccw(s.a, s.b, p) == 0;
}
bool intersect(const Line &l, const Segment &s) {
return cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < EPS;
}
Real distance(const Line &l, const Point &p);
bool intersect(const Circle &c, const Line &l) {
return distance(l, c.p) <= c.r + EPS;
}
bool intersect(const Circle &c, const Point &p) {
return abs(abs(p - c.p) - c.r) < EPS;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B
bool intersect(const Segment &s, const Segment &t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 && ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
int intersect(const Circle &c, const Segment &l) {
if(norm(projection(l, c.p) - c.p) - c.r * c.r > EPS) return 0;
auto d1 = abs(c.p - l.a), d2 = abs(c.p - l.b);
if(d1 < c.r + EPS && d2 < c.r + EPS) return 0;
if(d1 < c.r - EPS && d2 > c.r + EPS || d1 > c.r + EPS && d2 < c.r - EPS) return 1;
const Point h = projection(l, c.p);
if(dot(l.a - h, l.b - h) < 0) return 2;
return 0;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=jp
int intersect(Circle c1, Circle c2) {
if(c1.r < c2.r) swap(c1, c2);
Real d = abs(c1.p - c2.p);
if(c1.r + c2.r < d) return 4;
if(eq(c1.r + c2.r, d)) return 3;
if(c1.r - c2.r < d) return 2;
if(eq(c1.r - c2.r, d)) return 1;
return 0;
}
Real distance(const Point &a, const Point &b) {
return abs(a - b);
}
Real distance(const Line &l, const Point &p) {
return abs(p - projection(l, p));
}
Real distance(const Line &l, const Line &m) {
return intersect(l, m) ? 0 : distance(l, m.a);
}
Real distance(const Segment &s, const Point &p) {
Point r = projection(s, p);
if(intersect(s, r)) return abs(r - p);
return min(abs(s.a - p), abs(s.b - p));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D
Real distance(const Segment &a, const Segment &b) {
if(intersect(a, b)) return 0;
return min({distance(a, b.a), distance(a, b.b), distance(b, a.a), distance(b, a.b)});
}
Real distance(const Line &l, const Segment &s) {
if(intersect(l, s)) return 0;
return min(distance(l, s.a), distance(l, s.b));
}
Point crosspoint(const Line &l, const Line &m) {
Real A = cross(l.b - l.a, m.b - m.a);
Real B = cross(l.b - l.a, l.b - m.a);
if(eq(abs(A), 0.0) && eq(abs(B), 0.0)) return m.a;
return m.a + (m.b - m.a) * B / A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C
Point crosspoint(const Segment &l, const Segment &m) {
return crosspoint(Line(l), Line(m));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D
pair< Point, Point > crosspoint(const Circle &c, const Line l) {
Point pr = projection(l, c.p);
Point e = (l.b - l.a) / abs(l.b - l.a);
if(eq(distance(l, c.p), c.r)) return {pr, pr};
double base = sqrt(c.r * c.r - norm(pr - c.p));
return {pr - e * base, pr + e * base};
}
pair< Point, Point > crosspoint(const Circle &c, const Segment &l) {
Line aa = Line(l.a, l.b);
if(intersect(c, l) == 2) return crosspoint(c, aa);
auto ret = crosspoint(c, aa);
if(dot(l.a - ret.first, l.b - ret.first) < 0) ret.second = ret.first;
else ret.first = ret.second;
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E
pair< Point, Point > crosspoint(const Circle &c1, const Circle &c2) {
Real d = abs(c1.p - c2.p);
Real a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));
Real t = atan2(c2.p.imag() - c1.p.imag(), c2.p.real() - c1.p.real());
Point p1 = c1.p + Point(cos(t + a) * c1.r, sin(t + a) * c1.r);
Point p2 = c1.p + Point(cos(t - a) * c1.r, sin(t - a) * c1.r);
return {p1, p2};
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_F
pair< Point, Point > tangent(const Circle &c1, const Point &p2) {
return crosspoint(c1, Circle(p2, sqrt(norm(c1.p - p2) - c1.r * c1.r)));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_G
Lines tangent(Circle c1, Circle c2) {
Lines ret;
if(c1.r < c2.r) swap(c1, c2);
Real g = norm(c1.p - c2.p);
if(eq(g, 0)) return ret;
Point u = (c2.p - c1.p) / sqrt(g);
Point v = rotate(PI * 0.5, u);
for(int s : {-1, 1}) {
Real h = (c1.r + s * c2.r) / sqrt(g);
if(eq(1 - h * h, 0)) {
ret.emplace_back(c1.p + u * c1.r, c1.p + (u + v) * c1.r);
} else if(1 - h * h > 0) {
Point uu = u * h, vv = v * sqrt(1 - h * h);
ret.emplace_back(c1.p + (uu + vv) * c1.r, c2.p - (uu + vv) * c2.r * s);
ret.emplace_back(c1.p + (uu - vv) * c1.r, c2.p - (uu - vv) * c2.r * s);
}
}
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B
bool is_convex(const Polygon &p) {
int n = (int) p.size();
for(int i = 0; i < n; i++) {
if(ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == -1) return false;
}
return true;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A
Polygon convex_hull(Polygon &p) {
int n = (int) p.size(), k = 0;
if(n <= 2) return p;
sort(p.begin(), p.end());
vector< Point > ch(2 * n);
for(int i = 0; i < n; ch[k++] = p[i++]) {
while(k >= 2 && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {
while(k >= t && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
ch.resize(k - 1);
return ch;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C
enum {
OUT, ON, IN
};
int contains(const Polygon &Q, const Point &p) {
bool in = false;
for(int i = 0; i < Q.size(); i++) {
Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;
if(a.imag() > b.imag()) swap(a, b);
if(a.imag() <= 0 && 0 < b.imag() && cross(a, b) < 0) in = !in;
if(cross(a, b) == 0 && dot(a, b) <= 0) return ON;
}
return in ? IN : OUT;
}
bool merge_if_able(Segment &s1, const Segment &s2) {
if(abs(cross(s1.b - s1.a, s2.b - s2.a)) > EPS) return false;
if(ccw(s1.a, s2.a, s1.b) == 1 || ccw(s1.a, s2.a, s1.b) == -1) return false;
if(ccw(s1.a, s1.b, s2.a) == -2 || ccw(s2.a, s2.b, s1.a) == -2) return false;
s1 = Segment(min(s1.a, s2.a), max(s1.b, s2.b));
return true;
}
void merge_segments(vector< Segment > &segs) {
for(int i = 0; i < segs.size(); i++) {
if(segs[i].b < segs[i].a) swap(segs[i].a, segs[i].b);
}
for(int i = 0; i < segs.size(); i++) {
for(int j = i + 1; j < segs.size(); j++) {
if(merge_if_able(segs[i], segs[j])) {
segs[j--] = segs.back(), segs.pop_back();
}
}
}
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1033
vector< vector< int > > segment_arrangement(vector< Segment > &segs, vector< Point > &ps) {
vector< vector< int > > g;
int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(intersect(segs[i], segs[j])) {
ps.emplace_back(crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C
Polygon convex_cut(const Polygon &U, Line l) {
Polygon ret;
for(int i = 0; i < U.size(); i++) {
Point now = U[i], nxt = U[(i + 1) % U.size()];
if(ccw(l.a, l.b, now) != -1) ret.push_back(now);
if(ccw(l.a, l.b, now) * ccw(l.a, l.b, nxt) < 0) {
ret.push_back(crosspoint(Line(now, nxt), l));
}
}
return (ret);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A
Real area2(const Polygon &p) {
Real A = 0;
for(int i = 0; i < p.size(); ++i) {
A += cross(p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_H
Real area2(const Polygon &p, const Circle &c) {
if(p.size() < 3) return 0.0;
function< Real(Circle, Point, Point) > cross_area = [&](const Circle &c, const Point &a, const Point &b) {
Point va = c.p - a, vb = c.p - b;
Real f = cross(va, vb), ret = 0.0;
if(eq(f, 0.0)) return ret;
if(max(abs(va), abs(vb)) < c.r + EPS) return f;
if(distance(Segment(a, b), c.p) > c.r - EPS) return c.r * c.r * arg(vb * conj(va));
auto u = crosspoint(c, Segment(a, b));
vector< Point > tot{a, u.first, u.second, b};
for(int i = 0; i + 1 < tot.size(); i++) {
ret += cross_area(c, tot[i], tot[i + 1]);
}
return ret;
};
Real A = 0;
for(int i = 0; i < p.size(); i++) {
A += cross_area(c, p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B
Real convex_diameter(const Polygon &p) {
int N = (int) p.size();
int is = 0, js = 0;
for(int i = 1; i < N; i++) {
if(p[i].imag() > p[is].imag()) is = i;
if(p[i].imag() < p[js].imag()) js = i;
}
Real maxdis = norm(p[is] - p[js]);
int maxi, maxj, i, j;
i = maxi = is;
j = maxj = js;
do {
if(cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {
j = (j + 1) % N;
} else {
i = (i + 1) % N;
}
if(norm(p[i] - p[j]) > maxdis) {
maxdis = norm(p[i] - p[j]);
maxi = i;
maxj = j;
}
} while(i != is || j != js);
return sqrt(maxdis);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A
Real closest_pair(Points ps) {
if(ps.size() <= 1) throw (0);
sort(begin(ps), end(ps));
auto compare_y = [&](const Point &a, const Point &b) {
return imag(a) < imag(b);
};
vector< Point > beet(ps.size());
const Real INF = 1e18;
function< Real(int, int) > rec = [&](int left, int right) {
if(right - left <= 1) return INF;
int mid = (left + right) >> 1;
auto x = real(ps[mid]);
auto ret = min(rec(left, mid), rec(mid, right));
inplace_merge(begin(ps) + left, begin(ps) + mid, begin(ps) + right, compare_y);
int ptr = 0;
for(int i = left; i < right; i++) {
if(abs(real(ps[i]) - x) >= ret) continue;
for(int j = 0; j < ptr; j++) {
auto luz = ps[i] - beet[ptr - j - 1];
if(imag(luz) >= ret) break;
ret = min(ret, abs(luz));
}
beet[ptr++] = ps[i];
}
return ret;
};
return rec(0, (int) ps.size());
}
const Real INF = 1e18;
double GetAngle(const Point &a, const Point &b, const Point &c) {
const Point v = b - a, w = c - b;
double alpha = atan2(imag(v), real(v)), beta = atan2(imag(w), real(w));
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180.0 / PI;
return min(theta, 360.0 - theta);
}
Real dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps) {
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< Real > > min_cost(g.size(), vector< Real >(g.size(), INF));
typedef tuple< Real, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
Real cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + GetAngle(ps[pre], ps[cur], ps[to]);
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main() {
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
merge_segments(segs);
auto g = segment_arrangement(segs, ps);
double ret = dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
}
``` |
#include<bits/stdc++.h>
#define f first
#define s second
#define mp make_pair
#define pi M_PI
#define inf 1e14
#define eps (1e-8)
#define MAX 1000
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y+p.y);}
Point operator-(Point p){ return Point(x-p.x,y-p.y);}
Point operator*(double k){ return Point(x*k,y*k);}
Point operator/(double k){ return Point(x/k,y/k);}
bool operator<(Point p)const{ return (x!=p.x ? x<p.x : y<p.y);}
bool operator==(Point p)const{ return fabs(x-p.x)<eps && fabs(y-p.y)<eps;}
double abs(){ return sqrt(norm());}
double norm(){ return (x*x+y*y);}
};
typedef Point Vector;
typedef vector<Point> Polygon;
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(),Point p2=Point()):p1(p1),p2(p2){}
};
typedef Segment Line;
double norm(Vector a){ return (a.x*a.x+a.y*a.y);}
double abs(Vector a){ return sqrt(norm(a));}
double dot(Vector a,Vector b){ return (a.x*b.x+a.y*b.y);}
double cross(Vector a,Vector b){ return (a.x*b.y-a.y*b.x);}
bool isParallel(Segment s,Segment t){
return equals(cross(s.p1-s.p2,t.p1-t.p2),0.0);
}
int ccw(Point p0,Point p1,Point p2){
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>eps)return 1;
if(cross(a,b)<-eps)return -1;
if(dot(a,b)<-eps)return 2;
if(a.norm()<b.norm())return -2;
return 0;
}
bool intersect(Point p1,Point p2,Point p3,Point p4){
return (ccw(p1,p2,p3)*ccw(p1,p2,p4)<=0 &&
ccw(p3,p4,p1)*ccw(p3,p4,p2)<=0);
}
bool intersect(Segment s1,Segment s2){
return intersect(s1.p1,s1.p2,s2.p1,s2.p2);
}
Point getCrossPointLL(Line a,Line b){
double A=cross(a.p2-a.p1,b.p2-b.p1);
double B=cross(a.p2-a.p1,a.p2-b.p1);
if(abs(A)<eps || abs(B)<eps)return b.p1;
return b.p1+(b.p2-b.p1)*(B/A);
}
bool merge_if_able(Segment &s,Segment t) {
if(!isParallel(s,t))return false;
if(ccw(s.p1,t.p1,s.p2)==1 ||
ccw(s.p1,t.p1,s.p2)==-1)return false;
if(ccw(s.p1,s.p2,t.p1)==-2 ||
ccw(t.p1,t.p2,s.p1)==-2)return false;
s=Segment(min(s.p1,t.p1),max(s.p2,t.p2));
return true;
}
void merge(vector<Segment>& v) {
for(int i=0;i<v.size();i++){
if(v[i].p2<v[i].p1)swap(v[i].p2,v[i].p1);
}
for(int i=0;i<v.size();i++)
for(int j=i+1;j<v.size();j++)
if(merge_if_able(v[i],v[j]))
v[j--]=v.back(),v.pop_back();
}
typedef vector<vector<int> > Graph;
Graph SegmentArrangement(vector<Segment> v,vector<Point> &ps){
for(int i=0;i<v.size();i++){
ps.push_back(v[i].p1);
ps.push_back(v[i].p2);
for(int j=i+1;j<v.size();j++){
if(intersect(v[i],v[j]))ps.push_back(getCrossPointLL(v[i],v[j]));
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
Graph g(ps.size());
for(int i=0;i<v.size();i++){
vector<pair<double,int> > list;
for(int j=0;j<ps.size();j++)
if(ccw(v[i].p1,v[i].p2,ps[j])==0)
list.push_back(mp(norm(v[i].p1-ps[j]),j));
sort(list.begin(),list.end());
for(int j=0;j<list.size()-1;j++){
int a=list[j].s,b=list[j+1].s;
g[a].push_back(b);
g[b].push_back(a);
}
}
return g;
}
class State{
public:
int n,b;
double cost;
State(int n,int b,double cost):n(n),b(b),cost(cost){}
bool operator<(State s)const{
return s.cost-cost<-eps;
}
};
Graph e;
vector<Point> vp;
Point a,b;
double getAngle(Vector v1,Vector v2){
double r=dot(v1,v2)/(abs(v1)*abs(v2));
if(r<-1.0)r=-1.0;
if(1.0<r)r=1.0;
return (acos(r)*180.0/pi);
}
double dijkstra(){
int s=0,g=0;
double d[MAX][MAX];
priority_queue<State> pq;
for(int i=0;i<vp.size();i++){
if(vp[i]==a)s=i;
if(vp[i]==b)g=i;
}
for(int i=0;i<MAX;i++)for(int j=0;j<MAX;j++)d[i][j]=inf;
for(int i=0;i<e[s].size();i++){
d[e[s][i]][s]=0;
pq.push(State(e[s][i],s,0));
}
while(pq.size()){
State u=pq.top();
pq.pop();
if(u.n==g)return u.cost;
if(d[u.n][u.b]-u.cost<-eps)continue;
for(int i=0;i<e[u.n].size();i++){
int next=e[u.n][i];
if(next==u.b)continue;
double cost=getAngle(vp[u.n]-vp[u.b],vp[next]-vp[u.n]);
if(u.cost+cost-d[next][u.n]<-eps){
d[next][u.n]=u.cost+cost;
pq.push(State(next,u.n,d[next][u.n]));
}
}
}
return -1;
}
int main()
{
int n;
while(1){
cin>>n;
if(n==0)break;
vector<Segment> vs;
for(int i=0;i<n;i++){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
vs.push_back(Segment(Point(x1,y1),Point(x2,y2)));
}
cin>>a.x>>a.y>>b.x>>b.y;
vp.clear();
vp.push_back(a);
vp.push_back(b);
merge(vs);
e=SegmentArrangement(vs,vp);
double ans=dijkstra();
if(ans==-1)cout<<-1<<endl;
else printf("%.10f\n",dijkstra());
}
return 0;
} | ### Prompt
Develop a solution in CPP to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include<bits/stdc++.h>
#define f first
#define s second
#define mp make_pair
#define pi M_PI
#define inf 1e14
#define eps (1e-8)
#define MAX 1000
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y+p.y);}
Point operator-(Point p){ return Point(x-p.x,y-p.y);}
Point operator*(double k){ return Point(x*k,y*k);}
Point operator/(double k){ return Point(x/k,y/k);}
bool operator<(Point p)const{ return (x!=p.x ? x<p.x : y<p.y);}
bool operator==(Point p)const{ return fabs(x-p.x)<eps && fabs(y-p.y)<eps;}
double abs(){ return sqrt(norm());}
double norm(){ return (x*x+y*y);}
};
typedef Point Vector;
typedef vector<Point> Polygon;
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(),Point p2=Point()):p1(p1),p2(p2){}
};
typedef Segment Line;
double norm(Vector a){ return (a.x*a.x+a.y*a.y);}
double abs(Vector a){ return sqrt(norm(a));}
double dot(Vector a,Vector b){ return (a.x*b.x+a.y*b.y);}
double cross(Vector a,Vector b){ return (a.x*b.y-a.y*b.x);}
bool isParallel(Segment s,Segment t){
return equals(cross(s.p1-s.p2,t.p1-t.p2),0.0);
}
int ccw(Point p0,Point p1,Point p2){
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>eps)return 1;
if(cross(a,b)<-eps)return -1;
if(dot(a,b)<-eps)return 2;
if(a.norm()<b.norm())return -2;
return 0;
}
bool intersect(Point p1,Point p2,Point p3,Point p4){
return (ccw(p1,p2,p3)*ccw(p1,p2,p4)<=0 &&
ccw(p3,p4,p1)*ccw(p3,p4,p2)<=0);
}
bool intersect(Segment s1,Segment s2){
return intersect(s1.p1,s1.p2,s2.p1,s2.p2);
}
Point getCrossPointLL(Line a,Line b){
double A=cross(a.p2-a.p1,b.p2-b.p1);
double B=cross(a.p2-a.p1,a.p2-b.p1);
if(abs(A)<eps || abs(B)<eps)return b.p1;
return b.p1+(b.p2-b.p1)*(B/A);
}
bool merge_if_able(Segment &s,Segment t) {
if(!isParallel(s,t))return false;
if(ccw(s.p1,t.p1,s.p2)==1 ||
ccw(s.p1,t.p1,s.p2)==-1)return false;
if(ccw(s.p1,s.p2,t.p1)==-2 ||
ccw(t.p1,t.p2,s.p1)==-2)return false;
s=Segment(min(s.p1,t.p1),max(s.p2,t.p2));
return true;
}
void merge(vector<Segment>& v) {
for(int i=0;i<v.size();i++){
if(v[i].p2<v[i].p1)swap(v[i].p2,v[i].p1);
}
for(int i=0;i<v.size();i++)
for(int j=i+1;j<v.size();j++)
if(merge_if_able(v[i],v[j]))
v[j--]=v.back(),v.pop_back();
}
typedef vector<vector<int> > Graph;
Graph SegmentArrangement(vector<Segment> v,vector<Point> &ps){
for(int i=0;i<v.size();i++){
ps.push_back(v[i].p1);
ps.push_back(v[i].p2);
for(int j=i+1;j<v.size();j++){
if(intersect(v[i],v[j]))ps.push_back(getCrossPointLL(v[i],v[j]));
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
Graph g(ps.size());
for(int i=0;i<v.size();i++){
vector<pair<double,int> > list;
for(int j=0;j<ps.size();j++)
if(ccw(v[i].p1,v[i].p2,ps[j])==0)
list.push_back(mp(norm(v[i].p1-ps[j]),j));
sort(list.begin(),list.end());
for(int j=0;j<list.size()-1;j++){
int a=list[j].s,b=list[j+1].s;
g[a].push_back(b);
g[b].push_back(a);
}
}
return g;
}
class State{
public:
int n,b;
double cost;
State(int n,int b,double cost):n(n),b(b),cost(cost){}
bool operator<(State s)const{
return s.cost-cost<-eps;
}
};
Graph e;
vector<Point> vp;
Point a,b;
double getAngle(Vector v1,Vector v2){
double r=dot(v1,v2)/(abs(v1)*abs(v2));
if(r<-1.0)r=-1.0;
if(1.0<r)r=1.0;
return (acos(r)*180.0/pi);
}
double dijkstra(){
int s=0,g=0;
double d[MAX][MAX];
priority_queue<State> pq;
for(int i=0;i<vp.size();i++){
if(vp[i]==a)s=i;
if(vp[i]==b)g=i;
}
for(int i=0;i<MAX;i++)for(int j=0;j<MAX;j++)d[i][j]=inf;
for(int i=0;i<e[s].size();i++){
d[e[s][i]][s]=0;
pq.push(State(e[s][i],s,0));
}
while(pq.size()){
State u=pq.top();
pq.pop();
if(u.n==g)return u.cost;
if(d[u.n][u.b]-u.cost<-eps)continue;
for(int i=0;i<e[u.n].size();i++){
int next=e[u.n][i];
if(next==u.b)continue;
double cost=getAngle(vp[u.n]-vp[u.b],vp[next]-vp[u.n]);
if(u.cost+cost-d[next][u.n]<-eps){
d[next][u.n]=u.cost+cost;
pq.push(State(next,u.n,d[next][u.n]));
}
}
}
return -1;
}
int main()
{
int n;
while(1){
cin>>n;
if(n==0)break;
vector<Segment> vs;
for(int i=0;i<n;i++){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
vs.push_back(Segment(Point(x1,y1),Point(x2,y2)));
}
cin>>a.x>>a.y>>b.x>>b.y;
vp.clear();
vp.push_back(a);
vp.push_back(b);
merge(vs);
e=SegmentArrangement(vs,vp);
double ans=dijkstra();
if(ans==-1)cout<<-1<<endl;
else printf("%.10f\n",dijkstra());
}
return 0;
}
``` |
#include <cstdio>
#include <iostream>
#include <complex>
#include <cmath>
#include <vector>
#include <utility>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
#define EPS 1e-8
typedef double D;
typedef complex<D> P;
typedef const P &rP;
typedef pair<int,int> pii;
typedef pair<P,P> seg;
typedef vector<vector<int> > Graph;
namespace std{
bool operator< (rP a, rP b){
if(abs(real(a) - real(b)) > EPS){
return real(a) < real(b);
}
return imag(a) + EPS < imag(b);
}
};
D dot(rP a, rP b){
return real(a) * real(b) + imag(a) * imag(b);
}
D cross(rP a, rP b){
return real(a) * imag(b) - imag(a) * real(b);
}
double intersect(const seg &a, const seg &b){
P da12 = a.second - a.first;
P db21 = b.first - b.second;
P dab1 = b.first - a.first;
double D = cross(da12, db21);
if(abs(D) > EPS){
double t = cross(dab1, db21) / D;
double s = cross(da12, dab1) / D;
if(-EPS < s && s < 1.0 + EPS){
return t;
}
}
return 1e99;
}
enum{
LEFT = 1, RIGHT = 2, ON = 4, FRONT = 8, BACK = 16
};
int ccw(P a, P b, P c){
b -= a;
c -= a;
D r = cross(b, c);
if(r > EPS){ return LEFT; }
if(r < -EPS){ return RIGHT; }
if(dot(b, c) < -EPS){ return BACK; }
if(abs(b) + EPS < abs(c)){ return FRONT; }
return ON;
}
bool merge_if_able(seg &s, const seg &t){
if(abs(cross(s.second - s.first, t.second - t.first)) > EPS){
return false;
}
if(ccw(s.first, t.first, s.second) & (LEFT | RIGHT)){
return false;
}
if(ccw(s.first, s.second, t.first) == FRONT){ return false; }
if(ccw(t.first, t.second, s.first) == FRONT){ return false; }
s = seg(min(s.first, t.first), max(s.second, t.second));
return true;
}
void mergeseg(vector<seg> &vsg){
for(int i = 0; i < vsg.size(); ++i){
if(vsg[i].second < vsg[i].first){
swap(vsg[i].second, vsg[i].first);
}
}
int inc;
for(int i = 0; i < vsg.size(); i += inc){
inc = 1;
for(int j = i + 1; j < vsg.size(); ++j){
if(merge_if_able(vsg[i], vsg[j])){
inc = 0;
vsg[j--] = vsg.back();
vsg.pop_back();
}
}
}
}
void segarrange(vector<seg> ss, vector<P> &ps, Graph &g){
mergeseg(ss);
set<P> sps(ps.begin(), ps.end());
for(int i = 0; i < ss.size(); ++i){
sps.insert(ss[i].first);
sps.insert(ss[i].second);
P dif = ss[i].second - ss[i].first;
for(int j = i + 1; j < ss.size(); ++j){
double t = intersect(ss[i], ss[j]);
if(-EPS < t && t < 1.0 + EPS){
sps.insert(ss[i].first + t * dif);
}
}
}
ps.assign(sps.begin(), sps.end());
g.assign(ps.size(), vector<int>());
for(int i = 0; i < ss.size(); ++i){
vector<pair<D,int> > v;
for(int j = 0; j < ps.size(); ++j){
if(ccw(ss[i].first, ss[i].second, ps[j]) == ON){
v.push_back(make_pair(norm(ps[j] - ss[i].first), j));
}
}
sort(v.begin(), v.end());
for(int j = 1; j < v.size(); ++j){
int t = v[j-1].second;
int u = v[j].second;
g[t].push_back(u);
g[u].push_back(t);
}
}
}
double pi = acos(-1.0);
struct state{
int now, prev;
double r;
bool operator< (const state &s) const{
return r > s.r;
}
};
double rotangle(rP a, rP b, rP c){
double r = abs(arg(b - a) - arg(c - b));
while(r > pi){ r -= 2.0 * pi; }
return abs(r);
}
void solve(int n){
D x1, y1, x2, y2;
vector<seg> vsg(n);
vector<P> ps(2);
Graph g;
for(int i = 0; i < n; ++i){
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
vsg[i] = seg(P(x1, y1), P(x2, y2));
}
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
ps[0] = P(x1, y1);
ps[1] = P(x2, y2);
segarrange(vsg, ps, g);
vector<vector<D> > d(ps.size(), vector<D>(ps.size(), 1e99));
int start = lower_bound(ps.begin(), ps.end(), P(x1, y1)) - ps.begin();
int goal = lower_bound(ps.begin(), ps.end(), P(x2, y2)) - ps.begin();
priority_queue<state> pq;
for(int i = 0; i < g[start].size(); ++i){
int t = g[start][i];
pq.push((state){t, start, 0.0});
d[t][start] = 0.0;
}
while(!pq.empty()){
state s = pq.top();
pq.pop();
if(d[s.now][s.prev] != s.r){ continue; }
if(s.now == goal){
printf("%.10f\n", s.r / pi * 180.0);
return;
}
for(int i = 0; i < g[s.now].size(); ++i){
int t = g[s.now][i];
double r = s.r + rotangle(ps[s.prev], ps[s.now], ps[t]);
if(d[t][s.now] > r){
d[t][s.now] = r;
pq.push((state){t, s.now, r});
}
}
}
puts("-1");
}
int main(){
int n;
while(scanf("%d", &n), n){
solve(n);
}
} | ### Prompt
In CPP, your task is to solve the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <cstdio>
#include <iostream>
#include <complex>
#include <cmath>
#include <vector>
#include <utility>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
#define EPS 1e-8
typedef double D;
typedef complex<D> P;
typedef const P &rP;
typedef pair<int,int> pii;
typedef pair<P,P> seg;
typedef vector<vector<int> > Graph;
namespace std{
bool operator< (rP a, rP b){
if(abs(real(a) - real(b)) > EPS){
return real(a) < real(b);
}
return imag(a) + EPS < imag(b);
}
};
D dot(rP a, rP b){
return real(a) * real(b) + imag(a) * imag(b);
}
D cross(rP a, rP b){
return real(a) * imag(b) - imag(a) * real(b);
}
double intersect(const seg &a, const seg &b){
P da12 = a.second - a.first;
P db21 = b.first - b.second;
P dab1 = b.first - a.first;
double D = cross(da12, db21);
if(abs(D) > EPS){
double t = cross(dab1, db21) / D;
double s = cross(da12, dab1) / D;
if(-EPS < s && s < 1.0 + EPS){
return t;
}
}
return 1e99;
}
enum{
LEFT = 1, RIGHT = 2, ON = 4, FRONT = 8, BACK = 16
};
int ccw(P a, P b, P c){
b -= a;
c -= a;
D r = cross(b, c);
if(r > EPS){ return LEFT; }
if(r < -EPS){ return RIGHT; }
if(dot(b, c) < -EPS){ return BACK; }
if(abs(b) + EPS < abs(c)){ return FRONT; }
return ON;
}
bool merge_if_able(seg &s, const seg &t){
if(abs(cross(s.second - s.first, t.second - t.first)) > EPS){
return false;
}
if(ccw(s.first, t.first, s.second) & (LEFT | RIGHT)){
return false;
}
if(ccw(s.first, s.second, t.first) == FRONT){ return false; }
if(ccw(t.first, t.second, s.first) == FRONT){ return false; }
s = seg(min(s.first, t.first), max(s.second, t.second));
return true;
}
void mergeseg(vector<seg> &vsg){
for(int i = 0; i < vsg.size(); ++i){
if(vsg[i].second < vsg[i].first){
swap(vsg[i].second, vsg[i].first);
}
}
int inc;
for(int i = 0; i < vsg.size(); i += inc){
inc = 1;
for(int j = i + 1; j < vsg.size(); ++j){
if(merge_if_able(vsg[i], vsg[j])){
inc = 0;
vsg[j--] = vsg.back();
vsg.pop_back();
}
}
}
}
void segarrange(vector<seg> ss, vector<P> &ps, Graph &g){
mergeseg(ss);
set<P> sps(ps.begin(), ps.end());
for(int i = 0; i < ss.size(); ++i){
sps.insert(ss[i].first);
sps.insert(ss[i].second);
P dif = ss[i].second - ss[i].first;
for(int j = i + 1; j < ss.size(); ++j){
double t = intersect(ss[i], ss[j]);
if(-EPS < t && t < 1.0 + EPS){
sps.insert(ss[i].first + t * dif);
}
}
}
ps.assign(sps.begin(), sps.end());
g.assign(ps.size(), vector<int>());
for(int i = 0; i < ss.size(); ++i){
vector<pair<D,int> > v;
for(int j = 0; j < ps.size(); ++j){
if(ccw(ss[i].first, ss[i].second, ps[j]) == ON){
v.push_back(make_pair(norm(ps[j] - ss[i].first), j));
}
}
sort(v.begin(), v.end());
for(int j = 1; j < v.size(); ++j){
int t = v[j-1].second;
int u = v[j].second;
g[t].push_back(u);
g[u].push_back(t);
}
}
}
double pi = acos(-1.0);
struct state{
int now, prev;
double r;
bool operator< (const state &s) const{
return r > s.r;
}
};
double rotangle(rP a, rP b, rP c){
double r = abs(arg(b - a) - arg(c - b));
while(r > pi){ r -= 2.0 * pi; }
return abs(r);
}
void solve(int n){
D x1, y1, x2, y2;
vector<seg> vsg(n);
vector<P> ps(2);
Graph g;
for(int i = 0; i < n; ++i){
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
vsg[i] = seg(P(x1, y1), P(x2, y2));
}
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
ps[0] = P(x1, y1);
ps[1] = P(x2, y2);
segarrange(vsg, ps, g);
vector<vector<D> > d(ps.size(), vector<D>(ps.size(), 1e99));
int start = lower_bound(ps.begin(), ps.end(), P(x1, y1)) - ps.begin();
int goal = lower_bound(ps.begin(), ps.end(), P(x2, y2)) - ps.begin();
priority_queue<state> pq;
for(int i = 0; i < g[start].size(); ++i){
int t = g[start][i];
pq.push((state){t, start, 0.0});
d[t][start] = 0.0;
}
while(!pq.empty()){
state s = pq.top();
pq.pop();
if(d[s.now][s.prev] != s.r){ continue; }
if(s.now == goal){
printf("%.10f\n", s.r / pi * 180.0);
return;
}
for(int i = 0; i < g[s.now].size(); ++i){
int t = g[s.now][i];
double r = s.r + rotangle(ps[s.prev], ps[s.now], ps[t]);
if(d[t][s.now] > r){
d[t][s.now] = r;
pq.push((state){t, s.now, r});
}
}
}
puts("-1");
}
int main(){
int n;
while(scanf("%d", &n), n){
solve(n);
}
}
``` |
#include <iostream>
#include <cassert>
#include <vector>
#include <set>
#include <queue>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <complex>
#include <cmath>
using namespace std;
typedef long long ll;
typedef long double R;
typedef complex<R> P;
namespace std {
bool operator < (P a, P b) {
return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b);
}
bool operator > (P a, P b) {
return (b < a);
}
}
const R EPS = 1e-7;
const R PI = acos((R)(-1));
/*
-1 -> neg
0 -> near 0
1 -> pos
*/
int sgn(R a) {
if (a < -EPS) return -1;
if (a > EPS) return 1;
return 0;
}
int sgn(R a, R b) {
return sgn(b-a);
}
bool near(P a, P b) {
return !sgn(abs(a-b));
}
R cross(P a, P b) { return a.real()*b.imag() - a.imag()*b.real(); }
R dot(P a, P b) { return a.real()*b.real() + a.imag()*b.imag(); }
R ssqrt(R d) {
d = max<R>(0, d);
return sqrt(d);
}
R sacos(R d) {
d = max<R>(-1, d);
d = min<R>(1, d);
return acos(d);
}
R deg2rad(R x) {
return x/180*PI;
}
R rad2deg(R x) {
return x/PI*180;
}
//?§???????[0, 2*PI)???
R radNorP(R x) {
return fmod(fmod(x, 2*PI) + 2*PI, 2*PI);
}
//?§???????[-PI, PI)???
R radNorN(R x) {
x = radNorP(x);
if (x >= PI) x -= 2*PI;
return x;
}
/**
* radian??§???x???[l, r]?????\??£????????????????????\??????
* 0:OFF
* 1:IN
* 2:ON
*/
bool inR(R l, R r, R x) {
l = radNorP(l);
r = radNorP(r);
x = radNorP(x);
if (!sgn(l, x) || !sgn(r, x)) return 2;
if (!sgn(l, r)) return 0;
if (sgn(l, r) == 1) {
if (sgn(l, x) == 1 && sgn(x, r) == 1) return 1;
} else {
if (sgn(x, r) == 1 || sgn(l, x) == 1) return 1;
}
return 0;
}
/* 1->cclock
-1->clock
0->on
2->back
-2->front
*/
int ccw(P a, P b, P c) {
assert(!near(a, b));
if (near(a, c) || near(b, c)) return 0;
int s = sgn(cross(b-a, c-a));
if (s) return s;
if (dot(b-a, c-a) < 0) return 2;
if (dot(a-b, c-b) < 0) return -2;
return 0;
}
struct L {
P x, y;
L() {};
L(P x, P y) :x(x), y(y) {};
};
P vec(const L &l) {
return l.y - l.x;
}
R abs(const L &l) {
return abs(vec(l));
}
int crossLL(const L &l, const L &m, P &r) {
L mm = L(m.x - l.x, m.y - l.x);
mm.x *= polar<R>(1.0, -arg(vec(l)));
mm.y *= polar<R>(1.0, -arg(vec(l)));
if (sgn(vec(mm).imag()) == 0) {
if (sgn(mm.x.imag()) == 0) return -1;
return 0;
}
r = mm.x - vec(mm) * (mm.x.imag() / vec(mm).imag());
r *= polar<R>(1.0, arg(vec(l)));
r += l.x;
return 1;
}
int crossSS(const L &l, const L &m, P &r) {
int u = crossLL(l, m, r);
if (u == 0) return 0;
if (u == -1) {
int x = ccw(l.x, l.y, m.x);
int y = ccw(l.x, l.y, m.y);
if (x == 0) {
r = m.x;
return -1;
}
if (y == 0) {
r = m.y;
return -1;
}
if (x == y) return 0;
r = l.x;
return -1;
}
if (ccw(l.x, l.y, r) == 0 && ccw(m.x, m.y, r) == 0) return 1;
return 0;
}
/*
exec??§res??????????????¢?????\???
*/
const R INF = 1e12;
template<int V>
struct Dijkstra {
typedef R T;
typedef pair<T, int> P;
vector<P> g[V];
void init() {
for (int i = 0; i < V; i++) {
g[i].clear();
}
}
void add(int from, int to, T dist) {
g[from].push_back(P(dist, to));
}
T res[V];
void exec(int s) {
fill_n(res, V, INF);
priority_queue<P, vector<P>, greater<P>> q;
q.push(P(0, s));
res[s] = 0;
while (!q.empty()) {
P p = q.top(); q.pop();
if (res[p.second] < p.first) continue;
for (P e: g[p.second]) {
if (p.first+e.first < res[e.second]) {
res[e.second] = p.first+e.first;
q.push(P(e.first+p.first, e.second));
}
}
}
return;
}
};
typedef pair<P, int> E;
const int MN = 55;
Dijkstra<MN*MN*2> djk;
int n;
L l[MN];
R ar[MN];
P s, t;
vector<E> g[MN];
int xyd2id(int x, int y, int d) {
return (y*MN+x)*2+d;
}
R calc() {
djk.init();
for (int i = 0; i < MN; i++) {
g[i].clear();
}
for (int i = 0; i < n; i++) {
ar[i] = arg(vec(l[i]));
}
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
P p;
int u = crossSS(l[i], l[j], p);
if (u == 0) continue;
// printf("cross %d %d\n", i, j);
g[i].push_back(E(p, j));
g[j].push_back(E(p, i));
djk.add(xyd2id(i, j, 0), xyd2id(j, i, 0), abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(i, j, 0), xyd2id(j, i, 1), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(i, j, 1), xyd2id(j, i, 0), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(i, j, 1), xyd2id(j, i, 1), abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 0), xyd2id(i, j, 0), abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 0), xyd2id(i, j, 1), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 1), xyd2id(i, j, 0), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 1), xyd2id(i, j, 1), abs(radNorN(ar[i]-ar[j])));
}
}
for (int i = 0; i < n; i++) {
if (ccw(l[i].x, l[i].y, s) == 0) {
// printf("start %d\n", i);
g[i].push_back(E(s, MN-2));
djk.add(xyd2id(MN-2, MN-2, 0), xyd2id(i, MN-2, 0), 0);
djk.add(xyd2id(MN-2, MN-2, 0), xyd2id(i, MN-2, 1), 0);
}
}
for (int i = 0; i < n; i++) {
if (ccw(l[i].x, l[i].y, t) == 0) {
// printf("end %d\n", i);
g[i].push_back(E(t, MN-1));
djk.add(xyd2id(i, MN-1, 0), xyd2id(MN-1, MN-1, 0), 0);
djk.add(xyd2id(i, MN-1, 1), xyd2id(MN-1, MN-1, 0), 0);
}
}
for (int i = 0; i < n; i++) {
sort(g[i].begin(), g[i].end(), [&](const E &x, const E &y){
return abs(x.first-l[i].x) < abs(y.first-l[i].x);
});
for (int j = 0; j < (int)g[i].size() - 1; j++) {
int x = g[i][j].second, y = g[i][j+1].second;
djk.add(xyd2id(i, x, 0), xyd2id(i, y, 0), 0);
djk.add(xyd2id(i, y, 1), xyd2id(i, x, 1), 0);
if (sgn(abs(g[i][j].first-l[i].x), abs(g[i][j+1].first-l[i].x)) == 0) {
djk.add(xyd2id(i, x, 1), xyd2id(i, y, 1), 0);
djk.add(xyd2id(i, y, 0), xyd2id(i, x, 0), 0);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
djk.add(xyd2id(i, j, 0), xyd2id(i, j, 1), PI);
}
}
djk.exec(xyd2id(MN-2, MN-2, 0));
R res = djk.res[xyd2id(MN-1, MN-1, 0)];
if (res > INF/2) {
return -1;
}
return rad2deg(res);
}
int main() {
while (true) {
cin >> n;
if (!n) break;
for (int i = 0; i < n; i++) {
R x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
l[i] = L(P(x1, y1), P(x2, y2));
}
R sx, sy, tx, ty;
cin >> sx >> sy >> tx >> ty;
s = P(sx, sy);
t = P(tx, ty);
printf("%.20Lf\n", calc());
}
return 0;
} | ### Prompt
Generate a Cpp solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <iostream>
#include <cassert>
#include <vector>
#include <set>
#include <queue>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <complex>
#include <cmath>
using namespace std;
typedef long long ll;
typedef long double R;
typedef complex<R> P;
namespace std {
bool operator < (P a, P b) {
return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b);
}
bool operator > (P a, P b) {
return (b < a);
}
}
const R EPS = 1e-7;
const R PI = acos((R)(-1));
/*
-1 -> neg
0 -> near 0
1 -> pos
*/
int sgn(R a) {
if (a < -EPS) return -1;
if (a > EPS) return 1;
return 0;
}
int sgn(R a, R b) {
return sgn(b-a);
}
bool near(P a, P b) {
return !sgn(abs(a-b));
}
R cross(P a, P b) { return a.real()*b.imag() - a.imag()*b.real(); }
R dot(P a, P b) { return a.real()*b.real() + a.imag()*b.imag(); }
R ssqrt(R d) {
d = max<R>(0, d);
return sqrt(d);
}
R sacos(R d) {
d = max<R>(-1, d);
d = min<R>(1, d);
return acos(d);
}
R deg2rad(R x) {
return x/180*PI;
}
R rad2deg(R x) {
return x/PI*180;
}
//?§???????[0, 2*PI)???
R radNorP(R x) {
return fmod(fmod(x, 2*PI) + 2*PI, 2*PI);
}
//?§???????[-PI, PI)???
R radNorN(R x) {
x = radNorP(x);
if (x >= PI) x -= 2*PI;
return x;
}
/**
* radian??§???x???[l, r]?????\??£????????????????????\??????
* 0:OFF
* 1:IN
* 2:ON
*/
bool inR(R l, R r, R x) {
l = radNorP(l);
r = radNorP(r);
x = radNorP(x);
if (!sgn(l, x) || !sgn(r, x)) return 2;
if (!sgn(l, r)) return 0;
if (sgn(l, r) == 1) {
if (sgn(l, x) == 1 && sgn(x, r) == 1) return 1;
} else {
if (sgn(x, r) == 1 || sgn(l, x) == 1) return 1;
}
return 0;
}
/* 1->cclock
-1->clock
0->on
2->back
-2->front
*/
int ccw(P a, P b, P c) {
assert(!near(a, b));
if (near(a, c) || near(b, c)) return 0;
int s = sgn(cross(b-a, c-a));
if (s) return s;
if (dot(b-a, c-a) < 0) return 2;
if (dot(a-b, c-b) < 0) return -2;
return 0;
}
struct L {
P x, y;
L() {};
L(P x, P y) :x(x), y(y) {};
};
P vec(const L &l) {
return l.y - l.x;
}
R abs(const L &l) {
return abs(vec(l));
}
int crossLL(const L &l, const L &m, P &r) {
L mm = L(m.x - l.x, m.y - l.x);
mm.x *= polar<R>(1.0, -arg(vec(l)));
mm.y *= polar<R>(1.0, -arg(vec(l)));
if (sgn(vec(mm).imag()) == 0) {
if (sgn(mm.x.imag()) == 0) return -1;
return 0;
}
r = mm.x - vec(mm) * (mm.x.imag() / vec(mm).imag());
r *= polar<R>(1.0, arg(vec(l)));
r += l.x;
return 1;
}
int crossSS(const L &l, const L &m, P &r) {
int u = crossLL(l, m, r);
if (u == 0) return 0;
if (u == -1) {
int x = ccw(l.x, l.y, m.x);
int y = ccw(l.x, l.y, m.y);
if (x == 0) {
r = m.x;
return -1;
}
if (y == 0) {
r = m.y;
return -1;
}
if (x == y) return 0;
r = l.x;
return -1;
}
if (ccw(l.x, l.y, r) == 0 && ccw(m.x, m.y, r) == 0) return 1;
return 0;
}
/*
exec??§res??????????????¢?????\???
*/
const R INF = 1e12;
template<int V>
struct Dijkstra {
typedef R T;
typedef pair<T, int> P;
vector<P> g[V];
void init() {
for (int i = 0; i < V; i++) {
g[i].clear();
}
}
void add(int from, int to, T dist) {
g[from].push_back(P(dist, to));
}
T res[V];
void exec(int s) {
fill_n(res, V, INF);
priority_queue<P, vector<P>, greater<P>> q;
q.push(P(0, s));
res[s] = 0;
while (!q.empty()) {
P p = q.top(); q.pop();
if (res[p.second] < p.first) continue;
for (P e: g[p.second]) {
if (p.first+e.first < res[e.second]) {
res[e.second] = p.first+e.first;
q.push(P(e.first+p.first, e.second));
}
}
}
return;
}
};
typedef pair<P, int> E;
const int MN = 55;
Dijkstra<MN*MN*2> djk;
int n;
L l[MN];
R ar[MN];
P s, t;
vector<E> g[MN];
int xyd2id(int x, int y, int d) {
return (y*MN+x)*2+d;
}
R calc() {
djk.init();
for (int i = 0; i < MN; i++) {
g[i].clear();
}
for (int i = 0; i < n; i++) {
ar[i] = arg(vec(l[i]));
}
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
P p;
int u = crossSS(l[i], l[j], p);
if (u == 0) continue;
// printf("cross %d %d\n", i, j);
g[i].push_back(E(p, j));
g[j].push_back(E(p, i));
djk.add(xyd2id(i, j, 0), xyd2id(j, i, 0), abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(i, j, 0), xyd2id(j, i, 1), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(i, j, 1), xyd2id(j, i, 0), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(i, j, 1), xyd2id(j, i, 1), abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 0), xyd2id(i, j, 0), abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 0), xyd2id(i, j, 1), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 1), xyd2id(i, j, 0), PI-abs(radNorN(ar[i]-ar[j])));
djk.add(xyd2id(j, i, 1), xyd2id(i, j, 1), abs(radNorN(ar[i]-ar[j])));
}
}
for (int i = 0; i < n; i++) {
if (ccw(l[i].x, l[i].y, s) == 0) {
// printf("start %d\n", i);
g[i].push_back(E(s, MN-2));
djk.add(xyd2id(MN-2, MN-2, 0), xyd2id(i, MN-2, 0), 0);
djk.add(xyd2id(MN-2, MN-2, 0), xyd2id(i, MN-2, 1), 0);
}
}
for (int i = 0; i < n; i++) {
if (ccw(l[i].x, l[i].y, t) == 0) {
// printf("end %d\n", i);
g[i].push_back(E(t, MN-1));
djk.add(xyd2id(i, MN-1, 0), xyd2id(MN-1, MN-1, 0), 0);
djk.add(xyd2id(i, MN-1, 1), xyd2id(MN-1, MN-1, 0), 0);
}
}
for (int i = 0; i < n; i++) {
sort(g[i].begin(), g[i].end(), [&](const E &x, const E &y){
return abs(x.first-l[i].x) < abs(y.first-l[i].x);
});
for (int j = 0; j < (int)g[i].size() - 1; j++) {
int x = g[i][j].second, y = g[i][j+1].second;
djk.add(xyd2id(i, x, 0), xyd2id(i, y, 0), 0);
djk.add(xyd2id(i, y, 1), xyd2id(i, x, 1), 0);
if (sgn(abs(g[i][j].first-l[i].x), abs(g[i][j+1].first-l[i].x)) == 0) {
djk.add(xyd2id(i, x, 1), xyd2id(i, y, 1), 0);
djk.add(xyd2id(i, y, 0), xyd2id(i, x, 0), 0);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
djk.add(xyd2id(i, j, 0), xyd2id(i, j, 1), PI);
}
}
djk.exec(xyd2id(MN-2, MN-2, 0));
R res = djk.res[xyd2id(MN-1, MN-1, 0)];
if (res > INF/2) {
return -1;
}
return rad2deg(res);
}
int main() {
while (true) {
cin >> n;
if (!n) break;
for (int i = 0; i < n; i++) {
R x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
l[i] = L(P(x1, y1), P(x2, y2));
}
R sx, sy, tx, ty;
cin >> sx >> sy >> tx >> ty;
s = P(sx, sy);
t = P(tx, ty);
printf("%.20Lf\n", calc());
}
return 0;
}
``` |
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <complex>
#include <vector>
#include <set>
#include <queue>
using namespace std;
typedef complex<double> P;
typedef pair<P,P> L;
typedef vector<vector<vector<double> > > mat;
const int INF = 1 << 29;
const double EPS = 1e-7;
namespace std{
bool operator == (const P &a, const P &b){
return fabs(real(a-b)) < EPS && fabs(imag(a-b)) < EPS;
}
}
struct data{
P p;
set<int> s;
data(P p):p(p){s.clear();}
};
struct state{
int prev,now;
double cost;
state(int p=0, int n=0, double c=0):prev(p),now(n),cost(c){}
bool operator < (const state &s) const {
return cost > s.cost;
}
};
int n;
L l[50];
P s, g;
vector<data> v;
mat cost;
double dot(P a, P b){ return real(conj(a)*b); }
double cross(P a, P b){ return imag(conj(a)*b); }
int ccw(P a, P b, P c){
b -= a;
c -= a;
if(cross(b,c) > EPS) return 1;
if(cross(b,c) < -EPS) return -1;
if(dot(b,c) < -EPS) return 2;
if(norm(b) < norm(c)) return -2;
return 0;
}
bool isIntersect(L s1, L s2){
return ( ccw(s1.first,s1.second,s2.first) * ccw(s1.first,s1.second,s2.second) <= 0 &&
ccw(s2.first,s2.second,s1.first) * ccw(s2.first,s2.second,s1.second) <= 0 );
}
P crossPoint(pair<P,P> l, pair<P,P> m){
double A = cross(l.second - l.first, m.second - m.first);
double B = cross(l.second - l.first, l.second - m.first);
if(fabs(A) < EPS && fabs(B) < EPS) return m.first;
else if(fabs(A) >= EPS) return m.first + B / A * (m.second - m.first);
}
void makeP(){
v.clear();
for(int i=0;i<n;i++){
bool f=false,f2=false;
for(int j=0;j<v.size();j++){
if(v[j].p == l[i].first){
v[j].s.insert(i);
f = true;
}
if(v[j].p == l[i].second){
v[j].s.insert(i);
f2 = true;
}
}
if(!f){
v.push_back(data(l[i].first));
v[v.size()-1].s.insert(i);
}
if(!f2){
v.push_back(data(l[i].second));
v[v.size()-1].s.insert(i);
}
for(int j=i+1;j<n;j++){
if(!isIntersect(l[i],l[j])) continue;
P p = crossPoint(l[i],l[j]);
f = false;
for(int k=0;k<v.size();k++){
if(v[k].p == p){
v[k].s.insert(i);
v[k].s.insert(j);
f = true;
break;
}
}
if(!f){
v.push_back(data(p));
v[v.size()-1].s.insert(i);
v[v.size()-1].s.insert(j);
}
}
}
}
double calcCost(P p1, P p2, P p3){
double A = abs(p2-p3);
double B = abs(p3-p1);
double C = abs(p1-p2);
return 180.0 - acos((B*B + C*C - A*A) / (2.0 * B * C)) * 180.0 / M_PI;
};
void makeCost(){
cost.assign(v.size(), vector<vector<double> >(v.size(), vector<double>(v.size(),(double)INF)));
for(int i=0;i<v.size();i++){
for(int j=0;j<v.size();j++){
if(i == j) continue;
bool f = false;
for(int k=0;k<n;k++){
if(v[i].s.find(k) != v[i].s.end() && v[j].s.find(k) != v[j].s.end()){
f = true;
break;
}
}
if(!f) continue;
for(int k=0;k<v.size();k++){
if(i == k || j == k) continue;
f = false;
for(int l=0;l<n;l++){
if(v[k].s.find(l) != v[k].s.end() && v[j].s.find(l) != v[j].s.end()){
f = true;
break;
}
}
if(f) cost[i][j][k] = calcCost(v[j].p, v[i].p, v[k].p);
}
}
}
}
void solve(){
priority_queue<state> Q;
state u,u2;
vector<vector<double> > d(v.size(), vector<double>(v.size(), (double)INF));
if(s == g){
cout << 0 << endl;
return;
}
for(int i=0;i<v.size();i++){
if(s == v[i].p){
u.prev = i;
break;
}
}
for(int i=0;i<v.size();i++){
for(set<int>::iterator it = v[u.prev].s.begin(); it != v[u.prev].s.end(); it++){
if(i != u.prev && v[i].s.find(*it) != v[i].s.end()){
u.now = i;
d[u.prev][i] = 0;
Q.push(u);
}
}
}
while(!Q.empty()){
u = Q.top();
Q.pop();
if(v[u.now].p == g){
printf("%.7f\n",u.cost);
return;
}
for(int i=0;i<v.size();i++){
u2 = state(u.now, i, d[u.prev][u.now] + cost[u.prev][u.now][i]);
if(u2.cost < d[u.now][i]){
d[u.now][i] = u2.cost;
Q.push(u2);
}
}
}
cout << -1 << endl;
}
int main(){
while(cin >> n && n){
double x,y,x2,y2;
for(int i=0;i<n;i++){
double x,y,x2,y2;
cin >> x >> y >> x2 >> y2;
l[i] = L(P(x,y),P(x2,y2));
}
cin >> x >> y >> x2 >> y2;
s = P(x,y);
g = P(x2,y2);
makeP();
makeCost();
solve();
}
} | ### Prompt
Please provide a cpp coded solution to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <complex>
#include <vector>
#include <set>
#include <queue>
using namespace std;
typedef complex<double> P;
typedef pair<P,P> L;
typedef vector<vector<vector<double> > > mat;
const int INF = 1 << 29;
const double EPS = 1e-7;
namespace std{
bool operator == (const P &a, const P &b){
return fabs(real(a-b)) < EPS && fabs(imag(a-b)) < EPS;
}
}
struct data{
P p;
set<int> s;
data(P p):p(p){s.clear();}
};
struct state{
int prev,now;
double cost;
state(int p=0, int n=0, double c=0):prev(p),now(n),cost(c){}
bool operator < (const state &s) const {
return cost > s.cost;
}
};
int n;
L l[50];
P s, g;
vector<data> v;
mat cost;
double dot(P a, P b){ return real(conj(a)*b); }
double cross(P a, P b){ return imag(conj(a)*b); }
int ccw(P a, P b, P c){
b -= a;
c -= a;
if(cross(b,c) > EPS) return 1;
if(cross(b,c) < -EPS) return -1;
if(dot(b,c) < -EPS) return 2;
if(norm(b) < norm(c)) return -2;
return 0;
}
bool isIntersect(L s1, L s2){
return ( ccw(s1.first,s1.second,s2.first) * ccw(s1.first,s1.second,s2.second) <= 0 &&
ccw(s2.first,s2.second,s1.first) * ccw(s2.first,s2.second,s1.second) <= 0 );
}
P crossPoint(pair<P,P> l, pair<P,P> m){
double A = cross(l.second - l.first, m.second - m.first);
double B = cross(l.second - l.first, l.second - m.first);
if(fabs(A) < EPS && fabs(B) < EPS) return m.first;
else if(fabs(A) >= EPS) return m.first + B / A * (m.second - m.first);
}
void makeP(){
v.clear();
for(int i=0;i<n;i++){
bool f=false,f2=false;
for(int j=0;j<v.size();j++){
if(v[j].p == l[i].first){
v[j].s.insert(i);
f = true;
}
if(v[j].p == l[i].second){
v[j].s.insert(i);
f2 = true;
}
}
if(!f){
v.push_back(data(l[i].first));
v[v.size()-1].s.insert(i);
}
if(!f2){
v.push_back(data(l[i].second));
v[v.size()-1].s.insert(i);
}
for(int j=i+1;j<n;j++){
if(!isIntersect(l[i],l[j])) continue;
P p = crossPoint(l[i],l[j]);
f = false;
for(int k=0;k<v.size();k++){
if(v[k].p == p){
v[k].s.insert(i);
v[k].s.insert(j);
f = true;
break;
}
}
if(!f){
v.push_back(data(p));
v[v.size()-1].s.insert(i);
v[v.size()-1].s.insert(j);
}
}
}
}
double calcCost(P p1, P p2, P p3){
double A = abs(p2-p3);
double B = abs(p3-p1);
double C = abs(p1-p2);
return 180.0 - acos((B*B + C*C - A*A) / (2.0 * B * C)) * 180.0 / M_PI;
};
void makeCost(){
cost.assign(v.size(), vector<vector<double> >(v.size(), vector<double>(v.size(),(double)INF)));
for(int i=0;i<v.size();i++){
for(int j=0;j<v.size();j++){
if(i == j) continue;
bool f = false;
for(int k=0;k<n;k++){
if(v[i].s.find(k) != v[i].s.end() && v[j].s.find(k) != v[j].s.end()){
f = true;
break;
}
}
if(!f) continue;
for(int k=0;k<v.size();k++){
if(i == k || j == k) continue;
f = false;
for(int l=0;l<n;l++){
if(v[k].s.find(l) != v[k].s.end() && v[j].s.find(l) != v[j].s.end()){
f = true;
break;
}
}
if(f) cost[i][j][k] = calcCost(v[j].p, v[i].p, v[k].p);
}
}
}
}
void solve(){
priority_queue<state> Q;
state u,u2;
vector<vector<double> > d(v.size(), vector<double>(v.size(), (double)INF));
if(s == g){
cout << 0 << endl;
return;
}
for(int i=0;i<v.size();i++){
if(s == v[i].p){
u.prev = i;
break;
}
}
for(int i=0;i<v.size();i++){
for(set<int>::iterator it = v[u.prev].s.begin(); it != v[u.prev].s.end(); it++){
if(i != u.prev && v[i].s.find(*it) != v[i].s.end()){
u.now = i;
d[u.prev][i] = 0;
Q.push(u);
}
}
}
while(!Q.empty()){
u = Q.top();
Q.pop();
if(v[u.now].p == g){
printf("%.7f\n",u.cost);
return;
}
for(int i=0;i<v.size();i++){
u2 = state(u.now, i, d[u.prev][u.now] + cost[u.prev][u.now][i]);
if(u2.cost < d[u.now][i]){
d[u.now][i] = u2.cost;
Q.push(u2);
}
}
}
cout << -1 << endl;
}
int main(){
while(cin >> n && n){
double x,y,x2,y2;
for(int i=0;i<n;i++){
double x,y,x2,y2;
cin >> x >> y >> x2 >> y2;
l[i] = L(P(x,y),P(x2,y2));
}
cin >> x >> y >> x2 >> y2;
s = P(x,y);
g = P(x2,y2);
makeP();
makeCost();
solve();
}
}
``` |
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>
#include <sstream>
#include <bitset>
#include <assert.h>
#include <valarray>
#include <iterator>
#include <tuple>
using namespace std;
typedef long long int ll;
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
#define REP(i,x) for(int i=0;i<(int)(x);i++)
#define REPS(i,x) for(int i=1;i<=(int)(x);i++)
#define RREP(i,x) for(int i=((int)(x)-1);i>=0;i--)
#define RREPS(i,x) for(int i=((int)(x));i>0;i--)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)
#define RFOR(i,c) for(__typeof((c).rbegin())i=(c).rbegin();i!=(c).rend();i++)
#define ALL(container) (container).begin(), (container).end()
#define RALL(container) (container).rbegin(), (container).rend()
#define SZ(container) ((int)container.size())
#define mp(a,b) make_pair(a, b)
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
template<class T> ostream& operator<<(ostream &os, const vector<T> &t) {
os<<"["; FOR(it,t) {if(it!=t.begin()) os<<","; os<<*it;} os<<"]"; return os;
}
template<class T> ostream& operator<<(ostream &os, const set<T> &t) {
os<<"{"; FOR(it,t) {if(it!=t.begin()) os<<","; os<<*it;} os<<"}"; return os;
}
template<class S, class T> ostream& operator<<(ostream &os, const pair<S,T> &t) { return os<<"("<<t.first<<","<<t.second<<")";}
template<class S, class T> pair<S,T> operator+(const pair<S,T> &s, const pair<S,T> &t){ return pair<S,T>(s.first+t.first, s.second+t.second);}
template<class S, class T> pair<S,T> operator-(const pair<S,T> &s, const pair<S,T> &t){ return pair<S,T>(s.first-t.first, s.second-t.second);}
namespace geom{
#define X real()
#define Y imag()
#define at(i) ((*this)[i])
#define SELF (*this)
enum {TRUE = 1, FALSE = 0, BORDER = -1};
typedef int BOOL;
typedef double R;
const R INF = 1e8;
const R EPS = 1e-8;
const R PI = 3.1415926535897932384626;
inline int sig(const R &x) { return (abs(x) < EPS ? 0 : x > 0 ? 1 : -1); }
inline BOOL less(const R &x, const R &y) {return sig(x-y) ? x < y : BORDER;}
typedef complex<R> P;
inline R norm(const P &p){return p.X*p.X+p.Y*p.Y;}
inline R inp(const P& a, const P& b){return (conj(a)*b).X;}
inline R outp(const P& a, const P& b){return (conj(a)*b).Y;}
inline P unit(const P& p){return p/abs(p);}
inline P proj(const P &s, const P &t){return t*inp(s, t)/norm(t);}
inline int ccw(const P &s, const P &t, const P &p, int adv=0){
int res = sig(outp(t-s, p-s));
if(res || !adv) return res;
if(sig(inp(t-s, p-s)) < 0) return -2; // p-s-t
if(sig(inp(s-t, p-t)) < 0) return 2; // s-t-p
return 0; // s-p-t
}
struct L : public vector<P>{ // line
L(const P &p1, const P &p2){this->push_back(p1);this->push_back(p2);}
L(){}
P dir()const {return at(1) - at(0);}
BOOL online(const P &p)const {return !sig(outp(p-at(0), dir()));}
};
struct S : public L{ // segment
S(const P &p1, const P &p2):L(p1, p2){}
S(){}
BOOL online(const P &p)const {
if(!sig(norm(p - at(0))) || !sig(norm(p - at(1)))) return BORDER;
return !sig(abs(at(0)-p) + abs(at(1) - p) - abs(at(0) - at(1)));
}
};
struct C : public P{
R r;
BOOL inside(const P& p)const { return less(norm(p-SELF), r*r);}
};
struct G : public vector<P>{
S edge(int i)const {return S(at(i), at(i+1 == size() ? 0 : i+1));}
BOOL contains(const P &p)const {
R sum = .0;
REP(i, size()){
if(S(at(i), at((i+1)%size())).online(p)) return BORDER; // online
sum += arg((at(i) - p) / (at((i+1)%size()) - p));
}
return !!sig(sum);
}
R area(){
R sum = 0;
REP(i, size()) sum += outp(at(i), at((i+1)%size()));
return abs(sum / 2.);
}
G convex_hull(bool online = false){
if(size() < 2) return *this;
sort(ALL(*this));
G r;
r.resize((int)size()*2);
int k=0;
for(int i=0;i<size();r[k++]=at(i++))
while(k>1 && ccw(r[k-2], r[k-1], at(i)) < 1-online) k--;
int t = k;
for(int i=(int)size()-1;i>=0;r[k++]=at(i--))
while(k>t && ccw(r[k-2], r[k-1], at(i)) < 1-online) k--;
r.resize(k-1);
return r;
}
};
inline P proj(const P &s, const L &t){return t[0] + proj(s-t[0], t[1]-t[0]);}
BOOL intersect(const S &s, const S &t){
const int p = ccw(t[0], t[1], s[0], 1) * ccw(t[0], t[1], s[1], 1);
const int q = ccw(s[0], s[1], t[0], 1) * ccw(s[0], s[1], t[1], 1);
return (p>0||q>0) ? FALSE : (!p||!q) ? BORDER : TRUE;
}
BOOL intersect(const S &s, const L &l){
if(l.online(s[0]) || l.online(s[1])) return BORDER;
return (sig(outp(l.dir(), s[0]-l[0])) * sig(outp(l.dir(), s[1]-l[0])) <= 0);
}
R dist2(const L &l, const P &p){return norm(outp(l.dir(), p - l[0])) / norm(l.dir());}
R dist2(const S &s, const P &p){
if(inp(p-s[0], s.dir()) < EPS) return norm(p - s[0]);
if(inp(p-s[1], -s.dir()) < EPS) return norm(p - s[1]);
return dist2((const L &)s, p);
}
R dist2(const S &s, const L &l){
return intersect(s, l) ? .0 : min(dist2(l, s[0]), dist2(l, s[1]));
}
R dist2(const S &s, const S &t){
return intersect(s, t) ? .0 : min(min(dist2(s, t[0]), dist2(t, s[0])),
min(dist2(s, t[1]), dist2(t, s[1])));
}
template <class T> R dist2(const G &g, const T& t){ // todo: 内部に完全に含まれる場合
R res = INF;
REP(i, g.size()) res = min(res, dist2(g.edge(i), t));
return res;
}
template<class S, class T> R dist(const S& s, const T& t){return sqrt(dist2(s, t));}
inline BOOL intersect(const C &a, const C &b){
return less((a.r-b.r)*(a.r-b.r), norm(a-b)) + less(norm(a-b), (a.r+b.r)*(a.r+b.r)) - 1;
}
inline BOOL intersect(const C &c, const L &l){
return less(dist2(l, c), c.r*c.r);
}
inline BOOL intersect(const C &c, const S &s){
int d = less(dist2(s, c), c.r*c.r);
if(d != TRUE) return d;
int p = c.inside(s[0]), q = c.inside(s[1]);
return (p<0 || q<0) ? BORDER : p&q;
}
inline S crosspoint(const C &c1, const C &c2){
if(!intersect(c1, c2)) return S();
R d = abs(c1 - c2);
R x = (c1.r*c1.r - c2.r*c2.r + d*d) / (2*d);
R h = sqrt(c1.r*c1.r - x*x);
P u = unit(c2-c1);
return S(c1 + u*x + u*P(0,1)*h, c1 + u*x + u*P(0,-1)*h);
}
inline P crosspoint(const L &l, const L &m){
R A = outp(l.dir(), m.dir()), B = outp(l.dir(), l[1] - m[0]);
if(!sig(abs(A)) && !sig(abs(B))) return m[0]; // same line
if(abs(A) < EPS) assert(false); // !!!PRECONDITION NOT SATISFIED!!!
return m[0] + B / A * (m[1] - m[0]);
}
inline R commonarea(const C &a, const C &b){
if(less(norm(a-b), (a.r-b.r)*(a.r-b.r)) == TRUE) return min(a.r*a.r, b.r*b.r)*PI;
if(less((a.r+b.r)*(a.r+b.r), norm(a-b)) == TRUE) return .0;
double d = abs(a-b);
double rc = (d*d + a.r*a.r - b.r*b.r) / (2*d);
double theta = acos(rc / a.r);
double phi = acos((d - rc) / b.r);
return a.r*a.r*theta + b.r*b.r*phi - d*a.r*sin(theta);
}
struct Arrangement{
struct AEdge{
int u, v, t;
R cost;
AEdge(int u=0, int v=0, int t=0, R cost=0)
:u(u), v(v), t(t), cost(cost){}
};
typedef vector<vector<AEdge>> AGraph;
vector<P> p;
AGraph g;
Arrangement(){}
Arrangement(vector<S> seg){
int m = seg.size();
REP(i, m){
p.push_back(seg[i][0]);
p.push_back(seg[i][1]);
REP(j, i) if(sig(outp(seg[i].dir(), seg[j].dir())) && intersect(seg[i], seg[j]) == TRUE)
p.push_back(crosspoint(seg[i], seg[j]));
}
sort(ALL(p)); UNIQUE(p);
int n=p.size();
g.resize(n);
REP(i, m){
S &s = seg[i];
vector<pair<R, int>> ps;
REP(j, n) if(s.online(p[j])) ps.emplace_back(norm(p[j] - s[0]), j);
sort(ALL(ps));
REP(j, (int)ps.size()-1){
const int u=ps[j].second;
const int v=ps[j+1].second;
g[u].emplace_back(u, v, 0, abs(p[u] - p[v]));
g[v].emplace_back(v, u, 0, abs(p[u] - p[v]));
}
}
}
int getIdx(P q){
auto it = lower_bound(ALL(p), q);
if(it == p.end() || *it != q) return -1;
return it - p.begin();
}
};
#undef SELF
#undef at
}
using namespace geom;
namespace std{
bool operator<(const geom::P &a, const geom::P &b){return sig(a.X-b.X) ? a.X < b.X : a.Y < b.Y;}
istream& operator>>(istream &is, P &p){R x,y;is>>x>>y;p=P(x, y);return is;}
istream& operator>>(istream &is, L &l){l.resize(2);return is >> l[0] >> l[1];}
istream& operator>>(istream &is, C &c){return is >> (P &)c >> c.r;}
}
int n;
int main(){
ios::sync_with_stdio(false);
while(cin >> n, n){
vector<S> seg(n);
REP(i, n) cin >> seg[i];
P sp, tp;
int s, y;
cin >> sp >> tp;
Arrangement a(seg);
s = a.getIdx(sp);
y = a.getIdx(tp);
auto &g = a.g;
auto &p = a.p;
int m = p.size();
map<tuple<int,int,int>, R> d;
REP(j, m)FOR(e1, g[j])FOR(e2, g[j]){
int i=e1->v, k=e2->v;
d[make_tuple(i, j, k)] = abs(arg((p[j]-p[i]) / (p[k]-p[j])))/PI*180;
}
vector<vector<R>> dp(m, vector<R>(m, INF));
typedef pair<R, pii> T;
priority_queue<T, vector<T>, greater<T>> pq;
pq.emplace(.0, pii(-1, s));
R ans = INF;
while(!pq.empty()){
T t = pq.top(); pq.pop();
int i=t.second.first;
int j=t.second.second;
if(i >= 0 && dp[i][j] < t.first) continue;
if(j == y){
ans = t.first;
break;
}
FOR(e, g[j]){
const int k = e->v;
const double cost = (i == -1) ? .0 : t.first + d[make_tuple(i, j, k)];
if(dp[j][k] > cost){
dp[j][k] = cost;
pq.emplace(cost, pii(j, k));
}
}
}
if(ans == INF) printf("-1\n");
else printf("%.10f\n", ans);
}
return 0;
} | ### Prompt
Develop a solution in Cpp to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>
#include <sstream>
#include <bitset>
#include <assert.h>
#include <valarray>
#include <iterator>
#include <tuple>
using namespace std;
typedef long long int ll;
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
#define REP(i,x) for(int i=0;i<(int)(x);i++)
#define REPS(i,x) for(int i=1;i<=(int)(x);i++)
#define RREP(i,x) for(int i=((int)(x)-1);i>=0;i--)
#define RREPS(i,x) for(int i=((int)(x));i>0;i--)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();i++)
#define RFOR(i,c) for(__typeof((c).rbegin())i=(c).rbegin();i!=(c).rend();i++)
#define ALL(container) (container).begin(), (container).end()
#define RALL(container) (container).rbegin(), (container).rend()
#define SZ(container) ((int)container.size())
#define mp(a,b) make_pair(a, b)
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
template<class T> ostream& operator<<(ostream &os, const vector<T> &t) {
os<<"["; FOR(it,t) {if(it!=t.begin()) os<<","; os<<*it;} os<<"]"; return os;
}
template<class T> ostream& operator<<(ostream &os, const set<T> &t) {
os<<"{"; FOR(it,t) {if(it!=t.begin()) os<<","; os<<*it;} os<<"}"; return os;
}
template<class S, class T> ostream& operator<<(ostream &os, const pair<S,T> &t) { return os<<"("<<t.first<<","<<t.second<<")";}
template<class S, class T> pair<S,T> operator+(const pair<S,T> &s, const pair<S,T> &t){ return pair<S,T>(s.first+t.first, s.second+t.second);}
template<class S, class T> pair<S,T> operator-(const pair<S,T> &s, const pair<S,T> &t){ return pair<S,T>(s.first-t.first, s.second-t.second);}
namespace geom{
#define X real()
#define Y imag()
#define at(i) ((*this)[i])
#define SELF (*this)
enum {TRUE = 1, FALSE = 0, BORDER = -1};
typedef int BOOL;
typedef double R;
const R INF = 1e8;
const R EPS = 1e-8;
const R PI = 3.1415926535897932384626;
inline int sig(const R &x) { return (abs(x) < EPS ? 0 : x > 0 ? 1 : -1); }
inline BOOL less(const R &x, const R &y) {return sig(x-y) ? x < y : BORDER;}
typedef complex<R> P;
inline R norm(const P &p){return p.X*p.X+p.Y*p.Y;}
inline R inp(const P& a, const P& b){return (conj(a)*b).X;}
inline R outp(const P& a, const P& b){return (conj(a)*b).Y;}
inline P unit(const P& p){return p/abs(p);}
inline P proj(const P &s, const P &t){return t*inp(s, t)/norm(t);}
inline int ccw(const P &s, const P &t, const P &p, int adv=0){
int res = sig(outp(t-s, p-s));
if(res || !adv) return res;
if(sig(inp(t-s, p-s)) < 0) return -2; // p-s-t
if(sig(inp(s-t, p-t)) < 0) return 2; // s-t-p
return 0; // s-p-t
}
struct L : public vector<P>{ // line
L(const P &p1, const P &p2){this->push_back(p1);this->push_back(p2);}
L(){}
P dir()const {return at(1) - at(0);}
BOOL online(const P &p)const {return !sig(outp(p-at(0), dir()));}
};
struct S : public L{ // segment
S(const P &p1, const P &p2):L(p1, p2){}
S(){}
BOOL online(const P &p)const {
if(!sig(norm(p - at(0))) || !sig(norm(p - at(1)))) return BORDER;
return !sig(abs(at(0)-p) + abs(at(1) - p) - abs(at(0) - at(1)));
}
};
struct C : public P{
R r;
BOOL inside(const P& p)const { return less(norm(p-SELF), r*r);}
};
struct G : public vector<P>{
S edge(int i)const {return S(at(i), at(i+1 == size() ? 0 : i+1));}
BOOL contains(const P &p)const {
R sum = .0;
REP(i, size()){
if(S(at(i), at((i+1)%size())).online(p)) return BORDER; // online
sum += arg((at(i) - p) / (at((i+1)%size()) - p));
}
return !!sig(sum);
}
R area(){
R sum = 0;
REP(i, size()) sum += outp(at(i), at((i+1)%size()));
return abs(sum / 2.);
}
G convex_hull(bool online = false){
if(size() < 2) return *this;
sort(ALL(*this));
G r;
r.resize((int)size()*2);
int k=0;
for(int i=0;i<size();r[k++]=at(i++))
while(k>1 && ccw(r[k-2], r[k-1], at(i)) < 1-online) k--;
int t = k;
for(int i=(int)size()-1;i>=0;r[k++]=at(i--))
while(k>t && ccw(r[k-2], r[k-1], at(i)) < 1-online) k--;
r.resize(k-1);
return r;
}
};
inline P proj(const P &s, const L &t){return t[0] + proj(s-t[0], t[1]-t[0]);}
BOOL intersect(const S &s, const S &t){
const int p = ccw(t[0], t[1], s[0], 1) * ccw(t[0], t[1], s[1], 1);
const int q = ccw(s[0], s[1], t[0], 1) * ccw(s[0], s[1], t[1], 1);
return (p>0||q>0) ? FALSE : (!p||!q) ? BORDER : TRUE;
}
BOOL intersect(const S &s, const L &l){
if(l.online(s[0]) || l.online(s[1])) return BORDER;
return (sig(outp(l.dir(), s[0]-l[0])) * sig(outp(l.dir(), s[1]-l[0])) <= 0);
}
R dist2(const L &l, const P &p){return norm(outp(l.dir(), p - l[0])) / norm(l.dir());}
R dist2(const S &s, const P &p){
if(inp(p-s[0], s.dir()) < EPS) return norm(p - s[0]);
if(inp(p-s[1], -s.dir()) < EPS) return norm(p - s[1]);
return dist2((const L &)s, p);
}
R dist2(const S &s, const L &l){
return intersect(s, l) ? .0 : min(dist2(l, s[0]), dist2(l, s[1]));
}
R dist2(const S &s, const S &t){
return intersect(s, t) ? .0 : min(min(dist2(s, t[0]), dist2(t, s[0])),
min(dist2(s, t[1]), dist2(t, s[1])));
}
template <class T> R dist2(const G &g, const T& t){ // todo: 内部に完全に含まれる場合
R res = INF;
REP(i, g.size()) res = min(res, dist2(g.edge(i), t));
return res;
}
template<class S, class T> R dist(const S& s, const T& t){return sqrt(dist2(s, t));}
inline BOOL intersect(const C &a, const C &b){
return less((a.r-b.r)*(a.r-b.r), norm(a-b)) + less(norm(a-b), (a.r+b.r)*(a.r+b.r)) - 1;
}
inline BOOL intersect(const C &c, const L &l){
return less(dist2(l, c), c.r*c.r);
}
inline BOOL intersect(const C &c, const S &s){
int d = less(dist2(s, c), c.r*c.r);
if(d != TRUE) return d;
int p = c.inside(s[0]), q = c.inside(s[1]);
return (p<0 || q<0) ? BORDER : p&q;
}
inline S crosspoint(const C &c1, const C &c2){
if(!intersect(c1, c2)) return S();
R d = abs(c1 - c2);
R x = (c1.r*c1.r - c2.r*c2.r + d*d) / (2*d);
R h = sqrt(c1.r*c1.r - x*x);
P u = unit(c2-c1);
return S(c1 + u*x + u*P(0,1)*h, c1 + u*x + u*P(0,-1)*h);
}
inline P crosspoint(const L &l, const L &m){
R A = outp(l.dir(), m.dir()), B = outp(l.dir(), l[1] - m[0]);
if(!sig(abs(A)) && !sig(abs(B))) return m[0]; // same line
if(abs(A) < EPS) assert(false); // !!!PRECONDITION NOT SATISFIED!!!
return m[0] + B / A * (m[1] - m[0]);
}
inline R commonarea(const C &a, const C &b){
if(less(norm(a-b), (a.r-b.r)*(a.r-b.r)) == TRUE) return min(a.r*a.r, b.r*b.r)*PI;
if(less((a.r+b.r)*(a.r+b.r), norm(a-b)) == TRUE) return .0;
double d = abs(a-b);
double rc = (d*d + a.r*a.r - b.r*b.r) / (2*d);
double theta = acos(rc / a.r);
double phi = acos((d - rc) / b.r);
return a.r*a.r*theta + b.r*b.r*phi - d*a.r*sin(theta);
}
struct Arrangement{
struct AEdge{
int u, v, t;
R cost;
AEdge(int u=0, int v=0, int t=0, R cost=0)
:u(u), v(v), t(t), cost(cost){}
};
typedef vector<vector<AEdge>> AGraph;
vector<P> p;
AGraph g;
Arrangement(){}
Arrangement(vector<S> seg){
int m = seg.size();
REP(i, m){
p.push_back(seg[i][0]);
p.push_back(seg[i][1]);
REP(j, i) if(sig(outp(seg[i].dir(), seg[j].dir())) && intersect(seg[i], seg[j]) == TRUE)
p.push_back(crosspoint(seg[i], seg[j]));
}
sort(ALL(p)); UNIQUE(p);
int n=p.size();
g.resize(n);
REP(i, m){
S &s = seg[i];
vector<pair<R, int>> ps;
REP(j, n) if(s.online(p[j])) ps.emplace_back(norm(p[j] - s[0]), j);
sort(ALL(ps));
REP(j, (int)ps.size()-1){
const int u=ps[j].second;
const int v=ps[j+1].second;
g[u].emplace_back(u, v, 0, abs(p[u] - p[v]));
g[v].emplace_back(v, u, 0, abs(p[u] - p[v]));
}
}
}
int getIdx(P q){
auto it = lower_bound(ALL(p), q);
if(it == p.end() || *it != q) return -1;
return it - p.begin();
}
};
#undef SELF
#undef at
}
using namespace geom;
namespace std{
bool operator<(const geom::P &a, const geom::P &b){return sig(a.X-b.X) ? a.X < b.X : a.Y < b.Y;}
istream& operator>>(istream &is, P &p){R x,y;is>>x>>y;p=P(x, y);return is;}
istream& operator>>(istream &is, L &l){l.resize(2);return is >> l[0] >> l[1];}
istream& operator>>(istream &is, C &c){return is >> (P &)c >> c.r;}
}
int n;
int main(){
ios::sync_with_stdio(false);
while(cin >> n, n){
vector<S> seg(n);
REP(i, n) cin >> seg[i];
P sp, tp;
int s, y;
cin >> sp >> tp;
Arrangement a(seg);
s = a.getIdx(sp);
y = a.getIdx(tp);
auto &g = a.g;
auto &p = a.p;
int m = p.size();
map<tuple<int,int,int>, R> d;
REP(j, m)FOR(e1, g[j])FOR(e2, g[j]){
int i=e1->v, k=e2->v;
d[make_tuple(i, j, k)] = abs(arg((p[j]-p[i]) / (p[k]-p[j])))/PI*180;
}
vector<vector<R>> dp(m, vector<R>(m, INF));
typedef pair<R, pii> T;
priority_queue<T, vector<T>, greater<T>> pq;
pq.emplace(.0, pii(-1, s));
R ans = INF;
while(!pq.empty()){
T t = pq.top(); pq.pop();
int i=t.second.first;
int j=t.second.second;
if(i >= 0 && dp[i][j] < t.first) continue;
if(j == y){
ans = t.first;
break;
}
FOR(e, g[j]){
const int k = e->v;
const double cost = (i == -1) ? .0 : t.first + d[make_tuple(i, j, k)];
if(dp[j][k] > cost){
dp[j][k] = cost;
pq.emplace(cost, pii(j, k));
}
}
}
if(ans == INF) printf("-1\n");
else printf("%.10f\n", ans);
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
#define EPS (1e-6)
#define equal(a,b) (fabs(a-b) < EPS)
#define lt(a,b) (a-b < -EPS)
#define MAX 252
#define INF (1e9)
#define PI acos(-1)
struct Point{
double x,y;
Point(){}
Point(double x,double y) : x(x),y(y) {}
Point operator + (const Point &p)const{ return Point(x+p.x,y+p.y); }
Point operator - (const Point &p)const{ return Point(x-p.x,y-p.y); }
Point operator * (const double &k)const{ return Point(x*k,y*k); }
Point operator / (const double &k)const{ return Point(x/k,y/k); }
bool operator < (const Point &p)const{ return x != p.x ? x < p.x : y < p.y; }
bool operator == (const Point &p)const{ return (x == p.x && y == p.y); }
};
double dot(const Point &a,const Point &b){ return a.x*b.x+a.y*b.y; }
double cross(const Point &a,const Point &b){ return a.x*b.y - b.x*a.y; }
double norm(const Point &p){ return dot(p,p); }
double abs(const Point &p){ return sqrt(norm(p)); }
double dist(const Point &a,const Point &b){
return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2));
}
double toRad(double ang){ return ang*PI/180; }
double toAng(double rad){ return rad*180/PI; }
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
typedef Point Vector;
int ccw(const Point &p0,const Point &p1,const Point &p2){
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a,b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS) return CLOCKWISE;
if(dot(a,b) < -EPS) return ONLINE_BACK;
if(norm(a) < norm(b)) return ONLINE_FRONT;
return ON_SEGMENT;
}
double getAngle(const Point &a,const Point &b,const Point &c){
Vector v1 = b-a, v2 = c-b;
double aa = atan2(v1.y,v1.x),ba = atan2(v2.y,v2.x);
if(aa > ba) swap(aa,ba);
double ang = toAng(ba - aa);
return min(ang,360-ang);
}
struct Segment{
Point s,t;
Segment(){}
Segment(Point s,Point t) : s(s),t(t) {}
};
bool isIntersectSP(const Segment &s,const Point &p){
return (ccw(s.s,s.t,p) == 0);
}
bool isIntersectSS(const Segment &a,const Segment &b){
Point s[2] = {a.s,a.t}, t[2] = {b.s,b.t};
return (ccw(s[0],s[1],t[0])*ccw(s[0],s[1],t[1]) <= 0 &&
ccw(t[0],t[1],s[0])*ccw(t[0],t[1],s[1]) <= 0);
}
Point crosspointSS(const Segment &a,const Segment &b){
Vector va = a.t-a.s, vb = b.t-b.s;
double d = cross(vb,va);
if(abs(d) < EPS) return b.s;
return a.s+va*cross(vb,b.t-a.s)*(1.0/d);
}
typedef vector<int> Edges;
typedef vector<Edges> Graph;
Graph segmentArrangement(vector<Segment> &segs,vector<Point> &ps){
Graph G;
int N = segs.size();
ps.clear();
for(int i = 0 ; i < N ; i++){
ps.push_back(segs[i].s);
ps.push_back(segs[i].t);
for(int j = i+1 ; j < N ; j++){
Vector a = segs[i].t - segs[i].s;
Vector b = segs[j].t - segs[j].s;
if(equal(cross(a,b),0)) continue;
if(isIntersectSS(segs[i],segs[j])){
ps.push_back(crosspointSS(segs[i],segs[j]));
}
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
int N2 = ps.size();
G.resize(N2);
for(int i = 0 ; i < N ; i++){
vector<int> vec;
for(int j = 0 ; j < N2 ; j++){
if(isIntersectSP(segs[i],ps[j])){
vec.push_back(j);
}
}
sort(vec.begin(),vec.end());
for(int j = 0 ; j < (int)vec.size()-1 ; j++){
int u = vec[j], v = vec[j+1];
G[u].push_back(v);
G[v].push_back(u);
}
}
return G;
}
struct State{
double w;
int p,n;
State(){}
State(double w,int p,int n) :
w(w),p(p),n(n) {}
bool operator < (const State &s)const{
return w > s.w;
}
};
double dijkstra(Graph &G,Point &s,Point &t,vector<Point> &ps){
int idx = -1;
for(int i = 0 ; i < (int)ps.size() ; i++){
if(ps[i] == s){
idx = i;
}
}
double d[MAX][MAX];
for(int i = 0 ; i < MAX ; i++){
for(int j = 0 ; j < MAX ; j++){
d[i][j] = INF;
}
}
priority_queue<State> Q;
for(int i = 0 ; i < (int)G[idx].size() ; i++){
int to = G[idx][i];
Q.push(State(0,idx,to));
d[idx][to] = 0;
}
while(!Q.empty()){
State st = Q.top(); Q.pop();
int p = st.p,n = st.n;
double w = st.w;
if(lt(d[p][n],w)) continue;
Point p1 = ps[p],p2 = ps[n];
if(p2 == t) return d[p][n];
for(int i = 0 ; i < (int)G[n].size() ; i++){
int to = G[n][i];
if(p == to) continue;
Point p3 = ps[to];
double ncost = w + getAngle(p1,p2,p3);
if(lt(ncost,d[n][to])){
d[n][to] = ncost;
Q.push(State(d[n][to],n,to));
}
}
}
return INF;
}
int main(){
int N;
while(cin >> N, N){
Point s,t;
vector<Segment> segs(N);
for(int i = 0 ; i < N ; i++){
cin >> segs[i].s.x >> segs[i].s.y;
cin >> segs[i].t.x >> segs[i].t.y;
}
cin >> s.x >> s.y >> t.x >> t.y;
vector<Point> ps;
Graph G = segmentArrangement(segs,ps);
double res = dijkstra(G,s,t,ps);
if(res == INF){
cout << -1 << endl;
}else{
printf("%.12f\n",res);
}
}
return 0;
} | ### Prompt
Your challenge is to write a CPP solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define EPS (1e-6)
#define equal(a,b) (fabs(a-b) < EPS)
#define lt(a,b) (a-b < -EPS)
#define MAX 252
#define INF (1e9)
#define PI acos(-1)
struct Point{
double x,y;
Point(){}
Point(double x,double y) : x(x),y(y) {}
Point operator + (const Point &p)const{ return Point(x+p.x,y+p.y); }
Point operator - (const Point &p)const{ return Point(x-p.x,y-p.y); }
Point operator * (const double &k)const{ return Point(x*k,y*k); }
Point operator / (const double &k)const{ return Point(x/k,y/k); }
bool operator < (const Point &p)const{ return x != p.x ? x < p.x : y < p.y; }
bool operator == (const Point &p)const{ return (x == p.x && y == p.y); }
};
double dot(const Point &a,const Point &b){ return a.x*b.x+a.y*b.y; }
double cross(const Point &a,const Point &b){ return a.x*b.y - b.x*a.y; }
double norm(const Point &p){ return dot(p,p); }
double abs(const Point &p){ return sqrt(norm(p)); }
double dist(const Point &a,const Point &b){
return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2));
}
double toRad(double ang){ return ang*PI/180; }
double toAng(double rad){ return rad*180/PI; }
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
typedef Point Vector;
int ccw(const Point &p0,const Point &p1,const Point &p2){
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a,b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS) return CLOCKWISE;
if(dot(a,b) < -EPS) return ONLINE_BACK;
if(norm(a) < norm(b)) return ONLINE_FRONT;
return ON_SEGMENT;
}
double getAngle(const Point &a,const Point &b,const Point &c){
Vector v1 = b-a, v2 = c-b;
double aa = atan2(v1.y,v1.x),ba = atan2(v2.y,v2.x);
if(aa > ba) swap(aa,ba);
double ang = toAng(ba - aa);
return min(ang,360-ang);
}
struct Segment{
Point s,t;
Segment(){}
Segment(Point s,Point t) : s(s),t(t) {}
};
bool isIntersectSP(const Segment &s,const Point &p){
return (ccw(s.s,s.t,p) == 0);
}
bool isIntersectSS(const Segment &a,const Segment &b){
Point s[2] = {a.s,a.t}, t[2] = {b.s,b.t};
return (ccw(s[0],s[1],t[0])*ccw(s[0],s[1],t[1]) <= 0 &&
ccw(t[0],t[1],s[0])*ccw(t[0],t[1],s[1]) <= 0);
}
Point crosspointSS(const Segment &a,const Segment &b){
Vector va = a.t-a.s, vb = b.t-b.s;
double d = cross(vb,va);
if(abs(d) < EPS) return b.s;
return a.s+va*cross(vb,b.t-a.s)*(1.0/d);
}
typedef vector<int> Edges;
typedef vector<Edges> Graph;
Graph segmentArrangement(vector<Segment> &segs,vector<Point> &ps){
Graph G;
int N = segs.size();
ps.clear();
for(int i = 0 ; i < N ; i++){
ps.push_back(segs[i].s);
ps.push_back(segs[i].t);
for(int j = i+1 ; j < N ; j++){
Vector a = segs[i].t - segs[i].s;
Vector b = segs[j].t - segs[j].s;
if(equal(cross(a,b),0)) continue;
if(isIntersectSS(segs[i],segs[j])){
ps.push_back(crosspointSS(segs[i],segs[j]));
}
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
int N2 = ps.size();
G.resize(N2);
for(int i = 0 ; i < N ; i++){
vector<int> vec;
for(int j = 0 ; j < N2 ; j++){
if(isIntersectSP(segs[i],ps[j])){
vec.push_back(j);
}
}
sort(vec.begin(),vec.end());
for(int j = 0 ; j < (int)vec.size()-1 ; j++){
int u = vec[j], v = vec[j+1];
G[u].push_back(v);
G[v].push_back(u);
}
}
return G;
}
struct State{
double w;
int p,n;
State(){}
State(double w,int p,int n) :
w(w),p(p),n(n) {}
bool operator < (const State &s)const{
return w > s.w;
}
};
double dijkstra(Graph &G,Point &s,Point &t,vector<Point> &ps){
int idx = -1;
for(int i = 0 ; i < (int)ps.size() ; i++){
if(ps[i] == s){
idx = i;
}
}
double d[MAX][MAX];
for(int i = 0 ; i < MAX ; i++){
for(int j = 0 ; j < MAX ; j++){
d[i][j] = INF;
}
}
priority_queue<State> Q;
for(int i = 0 ; i < (int)G[idx].size() ; i++){
int to = G[idx][i];
Q.push(State(0,idx,to));
d[idx][to] = 0;
}
while(!Q.empty()){
State st = Q.top(); Q.pop();
int p = st.p,n = st.n;
double w = st.w;
if(lt(d[p][n],w)) continue;
Point p1 = ps[p],p2 = ps[n];
if(p2 == t) return d[p][n];
for(int i = 0 ; i < (int)G[n].size() ; i++){
int to = G[n][i];
if(p == to) continue;
Point p3 = ps[to];
double ncost = w + getAngle(p1,p2,p3);
if(lt(ncost,d[n][to])){
d[n][to] = ncost;
Q.push(State(d[n][to],n,to));
}
}
}
return INF;
}
int main(){
int N;
while(cin >> N, N){
Point s,t;
vector<Segment> segs(N);
for(int i = 0 ; i < N ; i++){
cin >> segs[i].s.x >> segs[i].s.y;
cin >> segs[i].t.x >> segs[i].t.y;
}
cin >> s.x >> s.y >> t.x >> t.y;
vector<Point> ps;
Graph G = segmentArrangement(segs,ps);
double res = dijkstra(G,s,t,ps);
if(res == INF){
cout << -1 << endl;
}else{
printf("%.12f\n",res);
}
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
#define EPS (1e-6)
#define equal(a,b) (fabs(a-b) < EPS)
#define lt(a,b) (a-b < -EPS)
#define MAX 252
#define INF (1e9)
#define PI acos(-1)
struct Point{
double x,y;
Point(){}
Point(double x,double y) : x(x),y(y) {}
Point operator + (const Point &p)const{ return Point(x+p.x,y+p.y); }
Point operator - (const Point &p)const{ return Point(x-p.x,y-p.y); }
Point operator * (const double &k)const{ return Point(x*k,y*k); }
Point operator / (const double &k)const{ return Point(x/k,y/k); }
bool operator < (const Point &p)const{ return x != p.x ? x < p.x : y < p.y; }
bool operator == (const Point &p)const{ return (x == p.x && y == p.y); }
};
double dot(const Point &a,const Point &b){ return a.x*b.x+a.y*b.y; }
double cross(const Point &a,const Point &b){ return a.x*b.y - b.x*a.y; }
double norm(const Point &p){ return dot(p,p); }
double abs(const Point &p){ return sqrt(norm(p)); }
double dist(const Point &a,const Point &b){
return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2));
}
double toAng(double rad){ return rad*180/PI; }
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
typedef Point Vector;
int ccw(const Point &p0,const Point &p1,const Point &p2){
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a,b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS) return CLOCKWISE;
if(dot(a,b) < -EPS) return ONLINE_BACK;
if(norm(a) < norm(b)) return ONLINE_FRONT;
return ON_SEGMENT;
}
double getAngle(const Point &a,const Point &b,const Point &c){
Vector v1 = b-a, v2 = c-b;
double aa = atan2(v1.y,v1.x),ba = atan2(v2.y,v2.x);
if(aa > ba) swap(aa,ba);
double ang = toAng(ba - aa);
return min(ang,360-ang);
}
struct Segment{
Point s,t;
Segment(){}
Segment(Point s,Point t) : s(s),t(t) {}
};
bool isIntersectSP(const Segment &s,const Point &p){
return (ccw(s.s,s.t,p) == 0);
}
bool isIntersectSS(const Segment &a,const Segment &b){
Point s[2] = {a.s,a.t}, t[2] = {b.s,b.t};
return (ccw(s[0],s[1],t[0])*ccw(s[0],s[1],t[1]) <= 0 &&
ccw(t[0],t[1],s[0])*ccw(t[0],t[1],s[1]) <= 0);
}
Point crosspointSS(const Segment &a,const Segment &b){
Vector va = a.t-a.s, vb = b.t-b.s;
double d = cross(vb,va);
if(abs(d) < EPS) return b.s;
return a.s+va*cross(vb,b.t-a.s)*(1.0/d);
}
typedef vector<vector<int> > Graph;
Graph segmentArrangement(vector<Segment> &segs,vector<Point> &ps){
Graph G;
int N = segs.size();
ps.clear();
for(int i = 0 ; i < N ; i++){
ps.push_back(segs[i].s);
ps.push_back(segs[i].t);
for(int j = i+1 ; j < N ; j++){
Vector a = segs[i].t - segs[i].s;
Vector b = segs[j].t - segs[j].s;
if(equal(cross(a,b),0)) continue;
if(isIntersectSS(segs[i],segs[j])){
ps.push_back(crosspointSS(segs[i],segs[j]));
}
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
int N2 = ps.size();
G.resize(N2);
for(int i = 0 ; i < N ; i++){
vector<int> vec;
for(int j = 0 ; j < N2 ; j++){
if(isIntersectSP(segs[i],ps[j])){
vec.push_back(j);
}
}
sort(vec.begin(),vec.end());
for(int j = 0 ; j < (int)vec.size()-1 ; j++){
int u = vec[j], v = vec[j+1];
G[u].push_back(v);
G[v].push_back(u);
}
}
return G;
}
struct State{
double w;
int p,n;
State(){}
State(double w,int p,int n) :
w(w),p(p),n(n) {}
bool operator < (const State &s)const{
return w > s.w;
}
};
double dijkstra(Graph &G,Point &s,Point &t,vector<Point> &ps){
int idx = -1;
for(int i = 0 ; i < (int)ps.size() ; i++){
if(ps[i] == s){
idx = i;
}
}
double d[MAX][MAX];
for(int i = 0 ; i < MAX ; i++){
for(int j = 0 ; j < MAX ; j++){
d[i][j] = INF;
}
}
priority_queue<State> Q;
for(int i = 0 ; i < (int)G[idx].size() ; i++){
int to = G[idx][i];
Q.push(State(0,idx,to));
d[idx][to] = 0;
}
while(!Q.empty()){
State st = Q.top(); Q.pop();
int p = st.p,n = st.n;
double w = st.w;
if(lt(d[p][n],w)) continue;
Point p1 = ps[p],p2 = ps[n];
if(p2 == t) return d[p][n];
for(int i = 0 ; i < (int)G[n].size() ; i++){
int to = G[n][i];
if(p == to) continue;
Point p3 = ps[to];
double ncost = w + getAngle(p1,p2,p3);
if(lt(ncost,d[n][to])){
d[n][to] = ncost;
Q.push(State(d[n][to],n,to));
}
}
}
return INF;
}
int main(){
int N;
while(cin >> N, N){
Point s,t;
vector<Segment> segs(N);
for(int i = 0 ; i < N ; i++){
cin >> segs[i].s.x >> segs[i].s.y;
cin >> segs[i].t.x >> segs[i].t.y;
}
cin >> s.x >> s.y >> t.x >> t.y;
vector<Point> ps;
Graph G = segmentArrangement(segs,ps);
double res = dijkstra(G,s,t,ps);
if(res == INF){
cout << -1 << endl;
}else{
printf("%.12f\n",res);
}
}
return 0;
} | ### Prompt
Please create a solution in Cpp to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define EPS (1e-6)
#define equal(a,b) (fabs(a-b) < EPS)
#define lt(a,b) (a-b < -EPS)
#define MAX 252
#define INF (1e9)
#define PI acos(-1)
struct Point{
double x,y;
Point(){}
Point(double x,double y) : x(x),y(y) {}
Point operator + (const Point &p)const{ return Point(x+p.x,y+p.y); }
Point operator - (const Point &p)const{ return Point(x-p.x,y-p.y); }
Point operator * (const double &k)const{ return Point(x*k,y*k); }
Point operator / (const double &k)const{ return Point(x/k,y/k); }
bool operator < (const Point &p)const{ return x != p.x ? x < p.x : y < p.y; }
bool operator == (const Point &p)const{ return (x == p.x && y == p.y); }
};
double dot(const Point &a,const Point &b){ return a.x*b.x+a.y*b.y; }
double cross(const Point &a,const Point &b){ return a.x*b.y - b.x*a.y; }
double norm(const Point &p){ return dot(p,p); }
double abs(const Point &p){ return sqrt(norm(p)); }
double dist(const Point &a,const Point &b){
return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2));
}
double toAng(double rad){ return rad*180/PI; }
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
typedef Point Vector;
int ccw(const Point &p0,const Point &p1,const Point &p2){
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a,b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS) return CLOCKWISE;
if(dot(a,b) < -EPS) return ONLINE_BACK;
if(norm(a) < norm(b)) return ONLINE_FRONT;
return ON_SEGMENT;
}
double getAngle(const Point &a,const Point &b,const Point &c){
Vector v1 = b-a, v2 = c-b;
double aa = atan2(v1.y,v1.x),ba = atan2(v2.y,v2.x);
if(aa > ba) swap(aa,ba);
double ang = toAng(ba - aa);
return min(ang,360-ang);
}
struct Segment{
Point s,t;
Segment(){}
Segment(Point s,Point t) : s(s),t(t) {}
};
bool isIntersectSP(const Segment &s,const Point &p){
return (ccw(s.s,s.t,p) == 0);
}
bool isIntersectSS(const Segment &a,const Segment &b){
Point s[2] = {a.s,a.t}, t[2] = {b.s,b.t};
return (ccw(s[0],s[1],t[0])*ccw(s[0],s[1],t[1]) <= 0 &&
ccw(t[0],t[1],s[0])*ccw(t[0],t[1],s[1]) <= 0);
}
Point crosspointSS(const Segment &a,const Segment &b){
Vector va = a.t-a.s, vb = b.t-b.s;
double d = cross(vb,va);
if(abs(d) < EPS) return b.s;
return a.s+va*cross(vb,b.t-a.s)*(1.0/d);
}
typedef vector<vector<int> > Graph;
Graph segmentArrangement(vector<Segment> &segs,vector<Point> &ps){
Graph G;
int N = segs.size();
ps.clear();
for(int i = 0 ; i < N ; i++){
ps.push_back(segs[i].s);
ps.push_back(segs[i].t);
for(int j = i+1 ; j < N ; j++){
Vector a = segs[i].t - segs[i].s;
Vector b = segs[j].t - segs[j].s;
if(equal(cross(a,b),0)) continue;
if(isIntersectSS(segs[i],segs[j])){
ps.push_back(crosspointSS(segs[i],segs[j]));
}
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
int N2 = ps.size();
G.resize(N2);
for(int i = 0 ; i < N ; i++){
vector<int> vec;
for(int j = 0 ; j < N2 ; j++){
if(isIntersectSP(segs[i],ps[j])){
vec.push_back(j);
}
}
sort(vec.begin(),vec.end());
for(int j = 0 ; j < (int)vec.size()-1 ; j++){
int u = vec[j], v = vec[j+1];
G[u].push_back(v);
G[v].push_back(u);
}
}
return G;
}
struct State{
double w;
int p,n;
State(){}
State(double w,int p,int n) :
w(w),p(p),n(n) {}
bool operator < (const State &s)const{
return w > s.w;
}
};
double dijkstra(Graph &G,Point &s,Point &t,vector<Point> &ps){
int idx = -1;
for(int i = 0 ; i < (int)ps.size() ; i++){
if(ps[i] == s){
idx = i;
}
}
double d[MAX][MAX];
for(int i = 0 ; i < MAX ; i++){
for(int j = 0 ; j < MAX ; j++){
d[i][j] = INF;
}
}
priority_queue<State> Q;
for(int i = 0 ; i < (int)G[idx].size() ; i++){
int to = G[idx][i];
Q.push(State(0,idx,to));
d[idx][to] = 0;
}
while(!Q.empty()){
State st = Q.top(); Q.pop();
int p = st.p,n = st.n;
double w = st.w;
if(lt(d[p][n],w)) continue;
Point p1 = ps[p],p2 = ps[n];
if(p2 == t) return d[p][n];
for(int i = 0 ; i < (int)G[n].size() ; i++){
int to = G[n][i];
if(p == to) continue;
Point p3 = ps[to];
double ncost = w + getAngle(p1,p2,p3);
if(lt(ncost,d[n][to])){
d[n][to] = ncost;
Q.push(State(d[n][to],n,to));
}
}
}
return INF;
}
int main(){
int N;
while(cin >> N, N){
Point s,t;
vector<Segment> segs(N);
for(int i = 0 ; i < N ; i++){
cin >> segs[i].s.x >> segs[i].s.y;
cin >> segs[i].t.x >> segs[i].t.y;
}
cin >> s.x >> s.y >> t.x >> t.y;
vector<Point> ps;
Graph G = segmentArrangement(segs,ps);
double res = dijkstra(G,s,t,ps);
if(res == INF){
cout << -1 << endl;
}else{
printf("%.12f\n",res);
}
}
return 0;
}
``` |
#include<complex>
#include<vector>
#include<set>
#include<iostream>
#include<stack>
#include<cmath>
#include<queue>
#define FRONT 0x01
#define RIGHT 0x02
#define BACK 0x04
#define LEFT 0x08
#define OVER 0x10
#define CIRCLE_SAME 0x01
#define CIRCLE_CONTAIN 0x02
#define CIRCLE_NO_CROSS 0x04
#define CIRCLE_ONE_CROSS 0x08
#define CIRCLE_ONE_INSIDE_CROSS 0x10
#define CIRCLE_TWO_CROSS 0x20
#define sc second
#define fr first
#define REP(i,n) for(int i = 0; i < (int)(n); ++i)
using namespace std;
typedef double elem;
typedef complex<elem> point, vec;
typedef pair<point, point> line, hline, seg, pp;
const double eps = 1.0e-6;
const double pi = acos(-1.0);
const double infty = 1e40;
point base(0,0);
// oÍ
ostream &operator<<(ostream &os, const pair<point,point> &p){
os << p.fr << "-" << p.sc;
return os;
}
// lZ
inline elem sq(elem a){ return a*a; }
inline elem cq(elem a){ return a*a*a; }
// pxÏ·
elem rad(elem deg){ return (deg/180)*pi; }
elem deg(elem rad){ return (rad*180)/pi; }
// ®¬_Ìô¢AÈÇ
bool eq(elem a, elem b){ return abs(a-b) < eps; }
bool lt(elem a, elem b){ return !eq(a,b) && a < b; }
bool leq(elem a, elem b){ return eq(a,b) || a < b; }
bool gt(elem a, elem b){ return !eq(a,b) && a > b; }
bool geq(elem a, elem b){ return eq(a,b) || a > b; }
bool ltz(elem a){ return lt( a, 0 ); }
bool gtz(elem a){ return gt( a, 0 ); }
bool eqv(vec a, vec b){ return eq( abs(b-a),0); }
bool is_zv(vec v){ return eq(abs(v),0); }
elem emax(elem a, elem b){ return gt(a,b)?a:b; }
elem emin(elem a, elem b){ return lt(a,b)?a:b; }
// _Iy[^
bool far(point a, point b){ return gtz( abs(b-a) ); }
bool near(point a, point b){ return leq( abs(b-a), 0 ); }
elem dot(vec a, vec b){ return (a.real() * b.real() + a.imag() * b.imag() ); }
elem cross(vec a, vec b){ return ( a.real() * b.imag() - a.imag() * b.real() ); }
// a©çbÜÅvñèÌpxAàpA]ñ]
elem varg(vec a, vec b){
elem ret=arg(a)-arg(b);
if(lt(ret,0))ret+=2*pi;
if(gt(ret,2*pi))ret-=2*pi;
if(eq(ret,2*pi))ret=0;
return ret;
}
elem arg(vec a, vec b){ return acos( dot(a,b) / ( abs(a) * abs(b) ) ); }
point rot(point p, elem theta){ return p * polar((elem)1.0, theta); }
point rotdeg(point p, elem deg){ return p * polar((elem)1.0, rad(deg)); }
point proj(line l, point p){
double t=dot(p-l.first,l.first-l.second)/abs(l.first-l.second);
return l.first + t*(l.first-l.second);
}
point reflect(line l, point p){ return p+2.0*(proj(l,p)-p); }
// ñ_Ô£A¼üÆ_ÌÅZ£AüªÆ_ÌÅZ£
elem dist(point a, point b){ return abs(a-b); }
elem dist_l(line l, point x){ return abs(cross(l.sc-l.fr,x-l.fr)) / abs(l.sc-l.fr); }
elem dist_seg(seg s, point x)
{
if( ltz( dot(s.sc-s.fr,x-s.fr) ) ) return abs(x-s.fr);
if( ltz( dot(s.fr-s.sc,x-s.sc) ) ) return abs(x-s.sc);
return dist_l(s,x);
}
// PÊxNgA@üxNgAPÊ@üxNg
vec uvec(vec a){ return a / abs(a); }
vec nmr(vec a){ return a * vec(0,-1); }
vec nml(vec a){ return a * vec(0,1); }
vec unmr(vec a){ return uvec( nmr(a) ); }
vec unml(vec a){ return uvec( nml(a) ); }
// ¼ðA½s»è
bool orth(point a1, point a2, point b1, point b2){ return eq( dot( a2 - a1, b2 - b1 ), 0 ); }
bool orth(vec v1, vec v2){ return eq( dot(v1, v2), 0 ); }
bool prll(point a1, point a2, point b1, point b2){ return eq( cross( a2 - a1, b2 - b1 ), 0 ); }
bool prll(vec v1, vec v2){ return eq( cross(v1, v2), 0 ); }
// CCW oXg¾ªA¸xÉæé
int ccw(point a, point b, point x){
b -= a;
x -= a;
// if( is_zv(b) || is_zv( x ) ) return ERROR;
if( gtz( cross(b,x) ) ) return LEFT;
if( ltz( cross(b,x) ) ) return RIGHT;
if( ltz( dot(b,x) ) ) return BACK;
if( lt( abs(b), abs(x) ) ) return FRONT;
return OVER;
}
// üªÌð·»è
bool intersectedSS(seg a, seg b)
{
if( ccw(a.fr,a.sc,b.fr)&OVER || ccw(a.fr,a.sc,b.sc)&OVER ) return true;
return
( ccw(a.fr,a.sc,b.fr) | ccw(a.fr,a.sc,b.sc) ) == (LEFT|RIGHT) &&
( ccw(b.fr,b.sc,a.fr) | ccw(b.fr,b.sc,a.sc) ) == (LEFT|RIGHT) ;
}
// ¼üÌð·»è
bool intersectedLL(line a, line b){ return !eq( cross(a.sc-a.fr,b.sc-b.fr), 0.0 ); }
// ð_vZ
point intersectionSS(seg a, seg b)
{
elem d1 = dist_l(b,a.fr);
elem d2 = dist_l(b,a.sc);
return a.fr + ( d1 / (d1 + d2 ) ) * (a.sc-a.fr);
}
point intersectionLL(line a, line b)
{
vec va = a.sc - a.fr;
vec vb = b.sc - b.fr;
return a.fr + va * ( cross(vb, b.fr - a.fr) / cross(vb,va) );
}
// üªð_êÅ
bool intersectionLL(line a, line b, point &ret){
return intersectedLL( a, b ) ? ret = intersectionLL( a, b ), true : false;
}
bool intersectionLH(line a, hline b, point &ret){
point tmp;
return intersectionLL(a,b,tmp) ? ( ccw(b.fr,b.sc,tmp)&(OVER|FRONT) ? ret=tmp, true : false ) : false;
}
bool intersectionLS(line l, seg s, point &ret){
point tmp;
return intersectionLL(l,s,tmp) ? ( ccw(s.fr,s.sc,tmp)&OVER ? ret=tmp, true : false ) : false;
}
bool intersectionHH(hline a, hline b, point &ret){
point tmp;
return intersectionLL(a,b,tmp) ? ( ccw(a.fr,a.sc,tmp)&(OVER|FRONT)&&ccw(b.fr,b.sc,tmp)&(OVER|FRONT) ? ret = tmp, true : false ) : false;
}
bool intersectionHS(hline a, seg s, point &ret){
point tmp;
return intersectionLS(a,s,tmp) ? ( ccw(a.fr,a.sc,tmp)&(OVER|FRONT) ? ret = tmp, true : false ) : false;
}
bool intersectionSS(seg a, seg b, point &ret){
return intersectedSS(a,b) ? ret = intersectionSS(a,b), true : false;
}
struct Node{
point p;
vector<int> con;
Node(){}
Node(point p):p(p){}
};
typedef vector<Node> Graph;
struct State{
int prev;
int now;
double cost;
State(int prev, int now, double cost):prev(prev),now(now),cost(cost){}
bool operator>(const State &t)const{
return cost > t.cost;
}
};
double weight(int pre, int now, int next, const Graph &G){
if( now == 0 ) return 0;
vec a(G[now].p-G[pre].p);
vec b(G[next].p-G[now].p);
double ret = varg( a, b );
// assert(ret>=0);
return gt(ret,pi)?2*pi-ret:ret;
}
double dijkstra(int st, const Graph &G){
double ret = infty;
priority_queue< State, vector<State>, greater<State> > pq;
bool vis[G.size()+1][G.size()];
double C[G.size()+1][G.size()];
for(int i = 0; i < G.size()+1; ++i){
for(int j = 0; j < G.size(); ++j){
vis[i][j]=false;
C[i][j]=infty;
}
}
pq.push( State(G.size(),st,0.0) );
C[G.size()][st]=0;
while(!pq.empty()){
State now = pq.top(); pq.pop();
//cout << " PREV : " << now.prev << " NOW : " << now.now << " COST : " << now.cost << endl;
vis[now.prev][now.now] = false;
/*
if( vis[ now.prev ][ now.now ] ) continue;
else{
vis[ now.prev ][ now.now ] =true;
if( now.now == 1 ){
//ret = emin( ret, now.cost );
continue;
}
}
*/
const vector<int> &con = G[now.now].con;
for(int i = 0; i < con.size(); ++i){
int nextid = con[i];
double newcost = now.cost + weight(now.prev, now.now, nextid, G);
if( lt( newcost, C[now.now][nextid] ) ){
C[now.now][nextid] = newcost;
if( !vis[now.now][nextid] ){
vis[now.now][nextid]=true;
State next( now.now, nextid, newcost );
pq.push( next );
}
}
}
}
for(int i = 0; i < G.size()+1; ++i){
ret = emin( ret, C[i][1] );
}
return ret;
}
struct Point{
point p;
bool operator<(const Point &t)const{
return eq(p.real(),t.p.real()) ? lt( p.imag(), t.p.imag() ) : lt(p.real(),t.p.real());
}
Point ():p(0,0){}
Point (point p):p(p){}
};
int main(){
while(true){
int n;
cin >> n;
if ( n == 0 ) break;
Graph G;
set<Point> exist_intersection;
vector<seg> segs;
for(int i = 0; i < n; ++i){
elem x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2;
segs.push_back( seg(point(x1,y1),point(x2,y2)) );
}
elem sx,sy,gx,gy;cin>>sx>>sy>>gx>>gy;
G.push_back(point(sx,sy));
exist_intersection.insert( Point(point(sx,sy)) );
if(exist_intersection.find(Point(point(gx,gy)))==exist_intersection.end()){
G.push_back(point(gx,gy));
exist_intersection.insert(Point(point(gx,gy)));
}else{
printf("0.0\n");continue;
}
for(int i = 0; i < segs.size(); ++i){
if( exist_intersection.find(Point(segs[i].fr))==exist_intersection.end()){
exist_intersection.insert(Point(segs[i].fr));
G.push_back( segs[i].fr );
}
if( exist_intersection.find(Point(segs[i].sc))==exist_intersection.end()){
exist_intersection.insert(Point(segs[i].sc));
G.push_back( segs[i].sc );
}
for(int j = 0; j < segs.size(); ++j){
if( i != j ){
point tmp;
if( intersectionSS( segs[i], segs[j], tmp ) ){
if( exist_intersection.find(Point(tmp)) == exist_intersection.end() ){
exist_intersection.insert( Point(tmp) );
G.push_back( Node(tmp) );
}
}
}
}
}
for(int i = 0; i < segs.size(); ++i){
for(int j = 0; j < G.size(); ++j){
for(int k = 0; k < G.size(); ++k){
if( j != k ){
if( ccw( segs[i].fr, segs[i].sc, G[j].p ) == OVER &&
ccw( segs[i].fr, segs[i].sc, G[k].p ) == OVER ){
//cout << G[j].p << ' ' << G[k].p << endl;
G[j].con.push_back( k );
G[k].con.push_back( j );
}
}
}
}
}
elem ans = deg( dijkstra( 0, G ) );
if( geq( ans, infty ) ){
printf("-1\n");
}else{
printf("%.11lf\n",ans);
}
}
return 0;
} | ### Prompt
Your task is to create a Cpp solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include<complex>
#include<vector>
#include<set>
#include<iostream>
#include<stack>
#include<cmath>
#include<queue>
#define FRONT 0x01
#define RIGHT 0x02
#define BACK 0x04
#define LEFT 0x08
#define OVER 0x10
#define CIRCLE_SAME 0x01
#define CIRCLE_CONTAIN 0x02
#define CIRCLE_NO_CROSS 0x04
#define CIRCLE_ONE_CROSS 0x08
#define CIRCLE_ONE_INSIDE_CROSS 0x10
#define CIRCLE_TWO_CROSS 0x20
#define sc second
#define fr first
#define REP(i,n) for(int i = 0; i < (int)(n); ++i)
using namespace std;
typedef double elem;
typedef complex<elem> point, vec;
typedef pair<point, point> line, hline, seg, pp;
const double eps = 1.0e-6;
const double pi = acos(-1.0);
const double infty = 1e40;
point base(0,0);
// oÍ
ostream &operator<<(ostream &os, const pair<point,point> &p){
os << p.fr << "-" << p.sc;
return os;
}
// lZ
inline elem sq(elem a){ return a*a; }
inline elem cq(elem a){ return a*a*a; }
// pxÏ·
elem rad(elem deg){ return (deg/180)*pi; }
elem deg(elem rad){ return (rad*180)/pi; }
// ®¬_Ìô¢AÈÇ
bool eq(elem a, elem b){ return abs(a-b) < eps; }
bool lt(elem a, elem b){ return !eq(a,b) && a < b; }
bool leq(elem a, elem b){ return eq(a,b) || a < b; }
bool gt(elem a, elem b){ return !eq(a,b) && a > b; }
bool geq(elem a, elem b){ return eq(a,b) || a > b; }
bool ltz(elem a){ return lt( a, 0 ); }
bool gtz(elem a){ return gt( a, 0 ); }
bool eqv(vec a, vec b){ return eq( abs(b-a),0); }
bool is_zv(vec v){ return eq(abs(v),0); }
elem emax(elem a, elem b){ return gt(a,b)?a:b; }
elem emin(elem a, elem b){ return lt(a,b)?a:b; }
// _Iy[^
bool far(point a, point b){ return gtz( abs(b-a) ); }
bool near(point a, point b){ return leq( abs(b-a), 0 ); }
elem dot(vec a, vec b){ return (a.real() * b.real() + a.imag() * b.imag() ); }
elem cross(vec a, vec b){ return ( a.real() * b.imag() - a.imag() * b.real() ); }
// a©çbÜÅvñèÌpxAàpA]ñ]
elem varg(vec a, vec b){
elem ret=arg(a)-arg(b);
if(lt(ret,0))ret+=2*pi;
if(gt(ret,2*pi))ret-=2*pi;
if(eq(ret,2*pi))ret=0;
return ret;
}
elem arg(vec a, vec b){ return acos( dot(a,b) / ( abs(a) * abs(b) ) ); }
point rot(point p, elem theta){ return p * polar((elem)1.0, theta); }
point rotdeg(point p, elem deg){ return p * polar((elem)1.0, rad(deg)); }
point proj(line l, point p){
double t=dot(p-l.first,l.first-l.second)/abs(l.first-l.second);
return l.first + t*(l.first-l.second);
}
point reflect(line l, point p){ return p+2.0*(proj(l,p)-p); }
// ñ_Ô£A¼üÆ_ÌÅZ£AüªÆ_ÌÅZ£
elem dist(point a, point b){ return abs(a-b); }
elem dist_l(line l, point x){ return abs(cross(l.sc-l.fr,x-l.fr)) / abs(l.sc-l.fr); }
elem dist_seg(seg s, point x)
{
if( ltz( dot(s.sc-s.fr,x-s.fr) ) ) return abs(x-s.fr);
if( ltz( dot(s.fr-s.sc,x-s.sc) ) ) return abs(x-s.sc);
return dist_l(s,x);
}
// PÊxNgA@üxNgAPÊ@üxNg
vec uvec(vec a){ return a / abs(a); }
vec nmr(vec a){ return a * vec(0,-1); }
vec nml(vec a){ return a * vec(0,1); }
vec unmr(vec a){ return uvec( nmr(a) ); }
vec unml(vec a){ return uvec( nml(a) ); }
// ¼ðA½s»è
bool orth(point a1, point a2, point b1, point b2){ return eq( dot( a2 - a1, b2 - b1 ), 0 ); }
bool orth(vec v1, vec v2){ return eq( dot(v1, v2), 0 ); }
bool prll(point a1, point a2, point b1, point b2){ return eq( cross( a2 - a1, b2 - b1 ), 0 ); }
bool prll(vec v1, vec v2){ return eq( cross(v1, v2), 0 ); }
// CCW oXg¾ªA¸xÉæé
int ccw(point a, point b, point x){
b -= a;
x -= a;
// if( is_zv(b) || is_zv( x ) ) return ERROR;
if( gtz( cross(b,x) ) ) return LEFT;
if( ltz( cross(b,x) ) ) return RIGHT;
if( ltz( dot(b,x) ) ) return BACK;
if( lt( abs(b), abs(x) ) ) return FRONT;
return OVER;
}
// üªÌð·»è
bool intersectedSS(seg a, seg b)
{
if( ccw(a.fr,a.sc,b.fr)&OVER || ccw(a.fr,a.sc,b.sc)&OVER ) return true;
return
( ccw(a.fr,a.sc,b.fr) | ccw(a.fr,a.sc,b.sc) ) == (LEFT|RIGHT) &&
( ccw(b.fr,b.sc,a.fr) | ccw(b.fr,b.sc,a.sc) ) == (LEFT|RIGHT) ;
}
// ¼üÌð·»è
bool intersectedLL(line a, line b){ return !eq( cross(a.sc-a.fr,b.sc-b.fr), 0.0 ); }
// ð_vZ
point intersectionSS(seg a, seg b)
{
elem d1 = dist_l(b,a.fr);
elem d2 = dist_l(b,a.sc);
return a.fr + ( d1 / (d1 + d2 ) ) * (a.sc-a.fr);
}
point intersectionLL(line a, line b)
{
vec va = a.sc - a.fr;
vec vb = b.sc - b.fr;
return a.fr + va * ( cross(vb, b.fr - a.fr) / cross(vb,va) );
}
// üªð_êÅ
bool intersectionLL(line a, line b, point &ret){
return intersectedLL( a, b ) ? ret = intersectionLL( a, b ), true : false;
}
bool intersectionLH(line a, hline b, point &ret){
point tmp;
return intersectionLL(a,b,tmp) ? ( ccw(b.fr,b.sc,tmp)&(OVER|FRONT) ? ret=tmp, true : false ) : false;
}
bool intersectionLS(line l, seg s, point &ret){
point tmp;
return intersectionLL(l,s,tmp) ? ( ccw(s.fr,s.sc,tmp)&OVER ? ret=tmp, true : false ) : false;
}
bool intersectionHH(hline a, hline b, point &ret){
point tmp;
return intersectionLL(a,b,tmp) ? ( ccw(a.fr,a.sc,tmp)&(OVER|FRONT)&&ccw(b.fr,b.sc,tmp)&(OVER|FRONT) ? ret = tmp, true : false ) : false;
}
bool intersectionHS(hline a, seg s, point &ret){
point tmp;
return intersectionLS(a,s,tmp) ? ( ccw(a.fr,a.sc,tmp)&(OVER|FRONT) ? ret = tmp, true : false ) : false;
}
bool intersectionSS(seg a, seg b, point &ret){
return intersectedSS(a,b) ? ret = intersectionSS(a,b), true : false;
}
struct Node{
point p;
vector<int> con;
Node(){}
Node(point p):p(p){}
};
typedef vector<Node> Graph;
struct State{
int prev;
int now;
double cost;
State(int prev, int now, double cost):prev(prev),now(now),cost(cost){}
bool operator>(const State &t)const{
return cost > t.cost;
}
};
double weight(int pre, int now, int next, const Graph &G){
if( now == 0 ) return 0;
vec a(G[now].p-G[pre].p);
vec b(G[next].p-G[now].p);
double ret = varg( a, b );
// assert(ret>=0);
return gt(ret,pi)?2*pi-ret:ret;
}
double dijkstra(int st, const Graph &G){
double ret = infty;
priority_queue< State, vector<State>, greater<State> > pq;
bool vis[G.size()+1][G.size()];
double C[G.size()+1][G.size()];
for(int i = 0; i < G.size()+1; ++i){
for(int j = 0; j < G.size(); ++j){
vis[i][j]=false;
C[i][j]=infty;
}
}
pq.push( State(G.size(),st,0.0) );
C[G.size()][st]=0;
while(!pq.empty()){
State now = pq.top(); pq.pop();
//cout << " PREV : " << now.prev << " NOW : " << now.now << " COST : " << now.cost << endl;
vis[now.prev][now.now] = false;
/*
if( vis[ now.prev ][ now.now ] ) continue;
else{
vis[ now.prev ][ now.now ] =true;
if( now.now == 1 ){
//ret = emin( ret, now.cost );
continue;
}
}
*/
const vector<int> &con = G[now.now].con;
for(int i = 0; i < con.size(); ++i){
int nextid = con[i];
double newcost = now.cost + weight(now.prev, now.now, nextid, G);
if( lt( newcost, C[now.now][nextid] ) ){
C[now.now][nextid] = newcost;
if( !vis[now.now][nextid] ){
vis[now.now][nextid]=true;
State next( now.now, nextid, newcost );
pq.push( next );
}
}
}
}
for(int i = 0; i < G.size()+1; ++i){
ret = emin( ret, C[i][1] );
}
return ret;
}
struct Point{
point p;
bool operator<(const Point &t)const{
return eq(p.real(),t.p.real()) ? lt( p.imag(), t.p.imag() ) : lt(p.real(),t.p.real());
}
Point ():p(0,0){}
Point (point p):p(p){}
};
int main(){
while(true){
int n;
cin >> n;
if ( n == 0 ) break;
Graph G;
set<Point> exist_intersection;
vector<seg> segs;
for(int i = 0; i < n; ++i){
elem x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2;
segs.push_back( seg(point(x1,y1),point(x2,y2)) );
}
elem sx,sy,gx,gy;cin>>sx>>sy>>gx>>gy;
G.push_back(point(sx,sy));
exist_intersection.insert( Point(point(sx,sy)) );
if(exist_intersection.find(Point(point(gx,gy)))==exist_intersection.end()){
G.push_back(point(gx,gy));
exist_intersection.insert(Point(point(gx,gy)));
}else{
printf("0.0\n");continue;
}
for(int i = 0; i < segs.size(); ++i){
if( exist_intersection.find(Point(segs[i].fr))==exist_intersection.end()){
exist_intersection.insert(Point(segs[i].fr));
G.push_back( segs[i].fr );
}
if( exist_intersection.find(Point(segs[i].sc))==exist_intersection.end()){
exist_intersection.insert(Point(segs[i].sc));
G.push_back( segs[i].sc );
}
for(int j = 0; j < segs.size(); ++j){
if( i != j ){
point tmp;
if( intersectionSS( segs[i], segs[j], tmp ) ){
if( exist_intersection.find(Point(tmp)) == exist_intersection.end() ){
exist_intersection.insert( Point(tmp) );
G.push_back( Node(tmp) );
}
}
}
}
}
for(int i = 0; i < segs.size(); ++i){
for(int j = 0; j < G.size(); ++j){
for(int k = 0; k < G.size(); ++k){
if( j != k ){
if( ccw( segs[i].fr, segs[i].sc, G[j].p ) == OVER &&
ccw( segs[i].fr, segs[i].sc, G[k].p ) == OVER ){
//cout << G[j].p << ' ' << G[k].p << endl;
G[j].con.push_back( k );
G[k].con.push_back( j );
}
}
}
}
}
elem ans = deg( dijkstra( 0, G ) );
if( geq( ans, infty ) ){
printf("-1\n");
}else{
printf("%.11lf\n",ans);
}
}
return 0;
}
``` |
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<complex>
#include<cmath>
using namespace std;
#define REP(i,N) for(int i=0;i<(int)(N);++i)
#define ALL(v) (v).begin(),(v).end()
typedef complex<double> P;
const double EPS = 1e-10;
const double PI = 4.0 * atan2(1, 1);
namespace std {
bool operator < (const P& a, const P& b) {
return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b);
}
}
inline double dot(P a, P b) {return real( conj(a)*b);}
inline double cross(P a, P b) {return imag( conj(a)*b);}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > EPS) return +1; // counter clockwise
if (cross(b, c) < -EPS) return -1; // clockwise
if (dot(b, c) < -EPS) return +2; // c--a--b on line
if (norm(b) + EPS < norm(c)) return -2; // a--b--c on line
return 0;
}
bool IsIntersectSS(P a1, P a2, P b1, P b2) {
return ccw(a1,a2,b1) * ccw(a1,a2,b2) <= 0 &&
ccw(b1,b2,a1) * ccw(b1,b2,a2) <= 0;
}
bool IsIntersectSP(P a, P b, P c) {
return (abs(a-c) + abs(c-b) < abs(a-b) + EPS);
}
P IntersectionLL(P a1,P a2,P b1, P b2) {
double A = cross(b2 - b1, a2 - a1);
double B = cross(b2 - b1, b2 - a1);
if (abs(A) < EPS && abs(B) < EPS) return a1; // same line
// if (abs(A) < EPS) assert(false); // !!!PRECONDITION NOT SATISFIED!!!
return a1 + B / A * (a2 - a1);
}
typedef vector<vector<int> > Graph;
Graph Arrangement(const vector<P> &from, const vector<P> &to, vector<P> &ps) {
REP(i, from.size()) {
ps.push_back( from[i] );
ps.push_back( to[i] );
REP(j, i) {
if( IsIntersectSS( from[i], to[i], from[j], to[j]) )
ps.push_back( IntersectionLL(from[i], to[i], from[j], to[j]));
}
}
sort(ALL(ps));
ps.erase(unique(ALL(ps)), ps.end());
Graph g(ps.size());
REP(i, from.size()) {
vector< pair<double, int> > onlines;
REP(j, ps.size()) {
if( IsIntersectSP(from[i], to[i], ps[j]) )
onlines.push_back( make_pair(norm(from[i] - ps[j]), j) );
}
sort( ALL(onlines) );
for(int j = 0; j + 1 < onlines.size(); j++) {
int a = onlines[j].second;
int b = onlines[j+1].second;
g[a].push_back(b);
g[b].push_back(a);
}
}
return g;
}
double memo[1024][1024];
struct State {
int pos, prev;
double cost;
bool operator<(const State& t) const {
return cost > t.cost;
}
double &ref() {
return memo[pos][prev];
}
};
int indexOf(const vector<P>& ps, P p) {
REP(i, ps.size()) {
if( norm( ps[i] - p ) < EPS )
return i;
}
return -1;
}
double Arg(P a, P b, P c) {
if( norm(b - a) < EPS ) return 0;
// if( ccw(a, b, c) == 2 || ccw(a, b, c) == 0 ) {return 0;}
double theta = arg( (c - b) / (b - a) );
theta = abs(theta);
// if( dot( b - a, c - b) < -EPS ) theta += PI / 2;
return theta;
}
double solve(Graph &g, vector<P> &ps, int si, int gi) {
REP(i, 1024) REP(j, 1024) memo[i][j] = 1e10;
priority_queue< State > up;
State s = (State){si, si,0};
up.push(s);
s.ref() = 0;
while( !up.empty() ) {
s = up.top(); up.pop();
if( s.pos == gi )
return s.cost;
for(int i = 0; i < g[s.pos].size(); i++) {
State next = s;
next.pos = g[s.pos][i];
next.prev = s.pos;
next.cost += Arg( ps[s.prev], ps[s.pos], ps[next.pos] );
if( next.ref() > next.cost + EPS ) {
next.ref() = next.cost;
up.push( next );
}
}
}
return -1;
}
int main() {
for(;;) {
int N; scanf("%d", &N);
if( N == 0 ) break;
vector<P> from, to;
REP(i, N) {
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
from.push_back( P(a, b) );
to.push_back( P(c, d) );
}
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
P start(a, b);
P goal(c, d);
vector<P> ps;
Graph g = Arrangement(from, to, ps);
int si = indexOf( ps, start );
int gi = indexOf( ps, goal );
double rad = solve(g, ps, si, gi);
if( rad < -0.5 ) {
cout << -1 << endl;
} else {
printf("%.8f\n", rad * 180 / PI);
}
}
} | ### Prompt
Create a solution in cpp for the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<complex>
#include<cmath>
using namespace std;
#define REP(i,N) for(int i=0;i<(int)(N);++i)
#define ALL(v) (v).begin(),(v).end()
typedef complex<double> P;
const double EPS = 1e-10;
const double PI = 4.0 * atan2(1, 1);
namespace std {
bool operator < (const P& a, const P& b) {
return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b);
}
}
inline double dot(P a, P b) {return real( conj(a)*b);}
inline double cross(P a, P b) {return imag( conj(a)*b);}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > EPS) return +1; // counter clockwise
if (cross(b, c) < -EPS) return -1; // clockwise
if (dot(b, c) < -EPS) return +2; // c--a--b on line
if (norm(b) + EPS < norm(c)) return -2; // a--b--c on line
return 0;
}
bool IsIntersectSS(P a1, P a2, P b1, P b2) {
return ccw(a1,a2,b1) * ccw(a1,a2,b2) <= 0 &&
ccw(b1,b2,a1) * ccw(b1,b2,a2) <= 0;
}
bool IsIntersectSP(P a, P b, P c) {
return (abs(a-c) + abs(c-b) < abs(a-b) + EPS);
}
P IntersectionLL(P a1,P a2,P b1, P b2) {
double A = cross(b2 - b1, a2 - a1);
double B = cross(b2 - b1, b2 - a1);
if (abs(A) < EPS && abs(B) < EPS) return a1; // same line
// if (abs(A) < EPS) assert(false); // !!!PRECONDITION NOT SATISFIED!!!
return a1 + B / A * (a2 - a1);
}
typedef vector<vector<int> > Graph;
Graph Arrangement(const vector<P> &from, const vector<P> &to, vector<P> &ps) {
REP(i, from.size()) {
ps.push_back( from[i] );
ps.push_back( to[i] );
REP(j, i) {
if( IsIntersectSS( from[i], to[i], from[j], to[j]) )
ps.push_back( IntersectionLL(from[i], to[i], from[j], to[j]));
}
}
sort(ALL(ps));
ps.erase(unique(ALL(ps)), ps.end());
Graph g(ps.size());
REP(i, from.size()) {
vector< pair<double, int> > onlines;
REP(j, ps.size()) {
if( IsIntersectSP(from[i], to[i], ps[j]) )
onlines.push_back( make_pair(norm(from[i] - ps[j]), j) );
}
sort( ALL(onlines) );
for(int j = 0; j + 1 < onlines.size(); j++) {
int a = onlines[j].second;
int b = onlines[j+1].second;
g[a].push_back(b);
g[b].push_back(a);
}
}
return g;
}
double memo[1024][1024];
struct State {
int pos, prev;
double cost;
bool operator<(const State& t) const {
return cost > t.cost;
}
double &ref() {
return memo[pos][prev];
}
};
int indexOf(const vector<P>& ps, P p) {
REP(i, ps.size()) {
if( norm( ps[i] - p ) < EPS )
return i;
}
return -1;
}
double Arg(P a, P b, P c) {
if( norm(b - a) < EPS ) return 0;
// if( ccw(a, b, c) == 2 || ccw(a, b, c) == 0 ) {return 0;}
double theta = arg( (c - b) / (b - a) );
theta = abs(theta);
// if( dot( b - a, c - b) < -EPS ) theta += PI / 2;
return theta;
}
double solve(Graph &g, vector<P> &ps, int si, int gi) {
REP(i, 1024) REP(j, 1024) memo[i][j] = 1e10;
priority_queue< State > up;
State s = (State){si, si,0};
up.push(s);
s.ref() = 0;
while( !up.empty() ) {
s = up.top(); up.pop();
if( s.pos == gi )
return s.cost;
for(int i = 0; i < g[s.pos].size(); i++) {
State next = s;
next.pos = g[s.pos][i];
next.prev = s.pos;
next.cost += Arg( ps[s.prev], ps[s.pos], ps[next.pos] );
if( next.ref() > next.cost + EPS ) {
next.ref() = next.cost;
up.push( next );
}
}
}
return -1;
}
int main() {
for(;;) {
int N; scanf("%d", &N);
if( N == 0 ) break;
vector<P> from, to;
REP(i, N) {
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
from.push_back( P(a, b) );
to.push_back( P(c, d) );
}
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
P start(a, b);
P goal(c, d);
vector<P> ps;
Graph g = Arrangement(from, to, ps);
int si = indexOf( ps, start );
int gi = indexOf( ps, goal );
double rad = solve(g, ps, si, gi);
if( rad < -0.5 ) {
cout << -1 << endl;
} else {
printf("%.8f\n", rad * 180 / PI);
}
}
}
``` |
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
if(s == g) {
cout << 0 << endl;
continue;
}
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) if(u != w) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
} | ### Prompt
Your task is to create a cpp solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
if(s == g) {
cout << 0 << endl;
continue;
}
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) if(u != w) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
}
``` |
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;
const double EPS = 1.0e-10;
const double PI = acos(-1.0);
class Point
{
public:
double y, x;
Point(){
y = x = 0.0;
}
Point(double y0, double x0){
y = y0;
x = x0;
}
Point operator+(const Point& p) const{
return Point(y + p.y, x + p.x);
}
Point operator-(const Point& p) const{
return Point(y - p.y, x - p.x);
}
Point operator*(double a) const{
return Point(y * a, x * a);
}
Point operator/(double a) const{
return Point(y / a, x / a);
}
double length() const{
return sqrt(y * y + x * x);
}
double dist(const Point& p) const{
return sqrt(pow(y - p.y, 2) + pow(x - p.x, 2));
}
double dot(const Point& p) const{
return y * p.y + x * p.x; // |a|*|b|*cosθ
}
double cross(const Point& p) const{
return x * p.y - y * p.x; // |a|*|b|*sinθ
}
};
double segmentPointDist(const Point& a1, const Point& a2, const Point& p)
{
if((a2-a1).dot(p-a1) < 0)
return a1.dist(p);
else if((a1-a2).dot(p-a2) < 0)
return a2.dist(p);
else
return abs((a2-a1).cross(p-a1)) / a1.dist(a2);
}
bool segmentsIntersection(const Point& a1, const Point& a2, const Point& b1, const Point& b2, Point& intersection)
{
double d = (a2 - a1).cross(b2 - b1);
if(abs(d) <= EPS){
if(segmentPointDist(a1, a2, b1) <= EPS){
intersection = b1;
return true;
}
if(segmentPointDist(a1, a2, b2) <= EPS){
intersection = b2;
return true;
}
return false;
}
double r = (b1 - a1).cross(b2 - b1) / d;
double s = (b1 - a1).cross(a2 - a1) / d;
if(r < -EPS || r > 1.0 + EPS || s < -EPS || s > 1.0 + EPS)
return false;
intersection = a1 * (1.0 - r) + a2 * r;
return true;
}
int main()
{
for(;;){
int n; // 線分の数
cin >> n;
if(n == 0)
return 0;
vector<Point> p1(n), p2(n); // 線分の端点
for(int i=0; i<n; ++i)
cin >> p1[i].x >> p1[i].y >> p2[i].x >> p2[i].y;
Point s, g;
cin >> s.x >> s.y >> g.x >> g.y;
vector<Point> p; // 線分の交点
p.push_back(s);
p.push_back(g);
for(int i=0; i<n; ++i){
for(int j=0; j<i; ++j){
Point intersection;
if(segmentsIntersection(p1[i], p2[i], p1[j], p2[j], intersection)){
bool same = false;
for(unsigned k=0; k<p.size(); ++k){
if(p[k].dist(intersection) < EPS)
same = true;
}
if(!same)
p.push_back(intersection);
}
}
}
int m = p.size(); // 線分の交点の数
vector<vector<int> > edges(m);
for(int i=0; i<m; ++i){
for(int j=0; j<i; ++j){
bool connect = false;
for(int k=0; k<n; ++k){
if(segmentPointDist(p1[k], p2[k], p[i]) < EPS && segmentPointDist(p1[k], p2[k], p[j]) < EPS)
connect = true;
}
if(connect){
edges[i].push_back(j);
edges[j].push_back(i);
}
}
}
map<pair<int, int>, double> check;
multimap<double, pair<int, int> > mm;
for(unsigned i=0; i<edges[0].size(); ++i){
check[make_pair(0, edges[0][i])] = 0.0;
mm.insert(make_pair(0.0, make_pair(0, edges[0][i])));
}
double ret = -1.0;
while(!mm.empty()){
double cost = mm.begin()->first;
int prev = mm.begin()->second.first;
int curr = mm.begin()->second.second;
mm.erase(mm.begin());
if(cost > check[make_pair(prev, curr)] + EPS)
continue;
if(curr == 1){
ret = cost;
break;
}
for(unsigned i=0; i<edges[curr].size(); ++i){
int next = edges[curr][i];
double theta = (p[next] - p[curr]).dot(p[curr] - p[prev]) / (p[next] - p[curr]).length() / (p[curr] - p[prev]).length();
theta = min(1.0, max(-1.0, theta));
theta = acos(theta);
double cost2 = cost + theta;
if(check.find(make_pair(curr, next)) == check.end() || cost2 < check[make_pair(curr, next)] - EPS){
check[make_pair(curr, next)] = cost2;
mm.insert(make_pair(cost2, make_pair(curr, next)));
}
}
}
if(ret < -0.5){
cout << -1 << endl;
}else{
ret *= 180 / PI;
cout << fixed << setprecision(10) << ret << endl;
}
}
} | ### Prompt
Create a solution in CPP for the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;
const double EPS = 1.0e-10;
const double PI = acos(-1.0);
class Point
{
public:
double y, x;
Point(){
y = x = 0.0;
}
Point(double y0, double x0){
y = y0;
x = x0;
}
Point operator+(const Point& p) const{
return Point(y + p.y, x + p.x);
}
Point operator-(const Point& p) const{
return Point(y - p.y, x - p.x);
}
Point operator*(double a) const{
return Point(y * a, x * a);
}
Point operator/(double a) const{
return Point(y / a, x / a);
}
double length() const{
return sqrt(y * y + x * x);
}
double dist(const Point& p) const{
return sqrt(pow(y - p.y, 2) + pow(x - p.x, 2));
}
double dot(const Point& p) const{
return y * p.y + x * p.x; // |a|*|b|*cosθ
}
double cross(const Point& p) const{
return x * p.y - y * p.x; // |a|*|b|*sinθ
}
};
double segmentPointDist(const Point& a1, const Point& a2, const Point& p)
{
if((a2-a1).dot(p-a1) < 0)
return a1.dist(p);
else if((a1-a2).dot(p-a2) < 0)
return a2.dist(p);
else
return abs((a2-a1).cross(p-a1)) / a1.dist(a2);
}
bool segmentsIntersection(const Point& a1, const Point& a2, const Point& b1, const Point& b2, Point& intersection)
{
double d = (a2 - a1).cross(b2 - b1);
if(abs(d) <= EPS){
if(segmentPointDist(a1, a2, b1) <= EPS){
intersection = b1;
return true;
}
if(segmentPointDist(a1, a2, b2) <= EPS){
intersection = b2;
return true;
}
return false;
}
double r = (b1 - a1).cross(b2 - b1) / d;
double s = (b1 - a1).cross(a2 - a1) / d;
if(r < -EPS || r > 1.0 + EPS || s < -EPS || s > 1.0 + EPS)
return false;
intersection = a1 * (1.0 - r) + a2 * r;
return true;
}
int main()
{
for(;;){
int n; // 線分の数
cin >> n;
if(n == 0)
return 0;
vector<Point> p1(n), p2(n); // 線分の端点
for(int i=0; i<n; ++i)
cin >> p1[i].x >> p1[i].y >> p2[i].x >> p2[i].y;
Point s, g;
cin >> s.x >> s.y >> g.x >> g.y;
vector<Point> p; // 線分の交点
p.push_back(s);
p.push_back(g);
for(int i=0; i<n; ++i){
for(int j=0; j<i; ++j){
Point intersection;
if(segmentsIntersection(p1[i], p2[i], p1[j], p2[j], intersection)){
bool same = false;
for(unsigned k=0; k<p.size(); ++k){
if(p[k].dist(intersection) < EPS)
same = true;
}
if(!same)
p.push_back(intersection);
}
}
}
int m = p.size(); // 線分の交点の数
vector<vector<int> > edges(m);
for(int i=0; i<m; ++i){
for(int j=0; j<i; ++j){
bool connect = false;
for(int k=0; k<n; ++k){
if(segmentPointDist(p1[k], p2[k], p[i]) < EPS && segmentPointDist(p1[k], p2[k], p[j]) < EPS)
connect = true;
}
if(connect){
edges[i].push_back(j);
edges[j].push_back(i);
}
}
}
map<pair<int, int>, double> check;
multimap<double, pair<int, int> > mm;
for(unsigned i=0; i<edges[0].size(); ++i){
check[make_pair(0, edges[0][i])] = 0.0;
mm.insert(make_pair(0.0, make_pair(0, edges[0][i])));
}
double ret = -1.0;
while(!mm.empty()){
double cost = mm.begin()->first;
int prev = mm.begin()->second.first;
int curr = mm.begin()->second.second;
mm.erase(mm.begin());
if(cost > check[make_pair(prev, curr)] + EPS)
continue;
if(curr == 1){
ret = cost;
break;
}
for(unsigned i=0; i<edges[curr].size(); ++i){
int next = edges[curr][i];
double theta = (p[next] - p[curr]).dot(p[curr] - p[prev]) / (p[next] - p[curr]).length() / (p[curr] - p[prev]).length();
theta = min(1.0, max(-1.0, theta));
theta = acos(theta);
double cost2 = cost + theta;
if(check.find(make_pair(curr, next)) == check.end() || cost2 < check[make_pair(curr, next)] - EPS){
check[make_pair(curr, next)] = cost2;
mm.insert(make_pair(cost2, make_pair(curr, next)));
}
}
}
if(ret < -0.5){
cout << -1 << endl;
}else{
ret *= 180 / PI;
cout << fixed << setprecision(10) << ret << endl;
}
}
}
``` |
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define int ll
#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=a;i--)
#define per(i,b) gnr(i,0,b)
#define pb push_back
#define eb emplace_back
#define a first
#define b second
#define bg begin()
#define ed end()
#define all(x) x.bg,x.ed
#ifdef LOCAL
#define dmp(x) cerr<<__LINE__<<" "<<#x<<" "<<x<<endl
#else
#define dmp(x) void(0)
#endif
template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(a>b)a=b;}
template<class t> using vc=vector<t>;
template<class t> using vvc=vc<vc<t>>;
using pi=pair<int,int>;
using vi=vc<int>;
template<class t,class u>
ostream& operator<<(ostream& os,const pair<t,u>& p){
return os<<"{"<<p.a<<","<<p.b<<"}";
}
template<class t> ostream& operator<<(ostream& os,const vc<t>& v){
os<<"{";
for(auto e:v)os<<e<<",";
return os<<"}";
}
template<class t> void mkuni(vc<t>&v){
sort(all(v));
v.erase(unique(all(v)),v.ed);
}
using ld=long double;
using cm=complex<ld>;
#define x real()
#define y imag()
const ld eps=1e-8;
const ld PI=acos(ld(-1));
int sgn(ld a){return a<-eps?-1:(a>eps?1:0);}
auto cmcmp=[](const cm&a,const cm&b){
if(sgn(a.x-b.x))return a.x<b.x;
else return sgn(a.y-b.y)<0;
};
auto cmeq=[](const cm&a,const cm&b){
return sgn(a.x-b.x)==0&&sgn(a.y-b.y)==0;
};
ld dot(cm a,cm b){return a.x*b.x+a.y*b.y;}
ld crs(cm a,cm b){return a.x*b.y-a.y*b.x;}
ld crs(cm a,cm b,cm c){return crs(b-a,c-a);}
int ccw(cm a,cm b){return sgn(crs(a,b));}
int ccw(cm a,cm b,cm c){return ccw(b-a,c-a);}
//AOJ1183
int qeq(ld a,ld b,ld c,ld&d,ld&e){
ld f=b*b-4*a*c;
if(sgn(f)<0)return 0;
ld g=sqrt(max(f,ld(0)));
d=(-b+g)/(2*a);
e=(-b-g)/(2*a);
return sgn(f)+1;
}
//(-2)[a,-1](0)[b,1](2)
int bet(cm a,cm b,cm c){
cm d=b-a;
ld e=dot(d,c-a);
if(sgn(e)<=0)return sgn(e)-1;
return sgn(e-norm(d))+1;
}
//AOJ0153
//0-no,1-edge,2-in
int cont(cm a,cm b,cm c,cm d){
if(ccw(a,b,c)==-1)
swap(b,c);
return min({ccw(a,b,d),ccw(b,c,d),ccw(c,a,d)})+1;
}
//AOJ1183
//arg between ab
//assume given lengths are valid
ld arg(ld a,ld b,ld c){
return acos(min(max((a*a+b*b-c*c)/(2*a*b),ld(-1)),ld(1)));
}
//AOJ2233
//a->b->c と進むときに曲がる角度
//a-b-cが一直線上にあれば0が帰る
ld turn(cm a,cm b,cm c){
return arg((c-b)/(b-a));
}
using ln=pair<cm,cm>;
cm dir(ln a){return a.b-a.a;}
cm eval(ln a,ld b){return a.a+dir(a)*b;}
int bet(ln a,cm b){return bet(a.a,a.b,b);}
cm proj(ln a,cm b){
cm c=dir(a);
return a.a+c*dot(c,b-a.a)/norm(c);
}
cm refl(ln a,cm b){
return ld(2)*proj(a,b)-b;
}
//AOJ0153
ld dsp(ln a,cm b){
cm c=proj(a,b);
if(abs(bet(a.a,a.b,c))<=1)return abs(b-c);
return min(abs(b-a.a),abs(b-a.b));
}
int ccw(ln a,cm b){return ccw(a.a,a.b,b);}
//AOJ1157
//0-no,1-yes(endpoint),2-yes(innner),3-overelap
int iss(ln a,ln b){
int c1=ccw(a.a,a.b,b.a),c2=ccw(a.a,a.b,b.b);
int d1=ccw(b.a,b.b,a.a),d2=ccw(b.a,b.b,a.b);
if(c1||c2||d1||d2)return 1-max(c1*c2,d1*d2);
int f=bet(a.a,a.b,b.a),g=bet(a.a,a.b,b.b);
if(max(f,g)==-2||min(f,g)==2)return 0;
return 3;
}
cm cll(ln a,ln b){
return eval(a,crs(b.a,b.b,a.a)/crs(dir(a),dir(b)));
}
//AOJ1157
ld dss(ln a,ln b){
if(iss(a,b))return 0;
return min({dsp(a,b.a),dsp(a,b.b),dsp(b,a.a),dsp(b,a.b)});
}
bool inc(int a,int b,int c){return a<=b&&b<=c;}
template<class E,class D=ll>
vc<D> dijkstra(const vvc<E>& g,int s){
const int n=g.size();
using P=pair<D,int>;
priority_queue<P,vc<P>,greater<P>> pq;
vc<D> dist(n,1e9);
const auto ar=[&](int v,D d){
if(dist[v]>d){
dist[v]=d;
pq.push(P(d,v));
}
};
ar(s,0);
while(pq.size()){
D d;
int v;
tie(d,v)=pq.top();pq.pop();
for(auto e:g[v])
ar(e.to,d+e.cost);
}
return dist;
}
signed main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout<<fixed<<setprecision(20);
while(1){
int n;cin>>n;
if(n==0)break;
vc<ln> w;
rep(i,n){
ld a,b,c,d;
cin>>a>>b>>c>>d;
w.eb(cm(a,b),cm(c,d));
}
vc<cm> pos;
rep(i,n){
pos.pb(w[i].a);
pos.pb(w[i].b);
}
rep(i,n)rep(j,i){
if(inc(1,iss(w[i],w[j]),2))
pos.pb(cll(w[i],w[j]));
}
sort(all(pos),cmcmp);
pos.erase(unique(all(pos),cmeq),pos.ed);
const auto idx=[&](cm a){
return lower_bound(all(pos),a,cmcmp)-pos.bg;
};
int s=pos.size();
vvc<pi> g(s);
int m=0;
rep(i,n){
vc<cm> z{w[i].a,w[i].b};
rep(j,n)if(i!=j){
int a=iss(w[i],w[j]);
if(a==1||a==2){
z.pb(cll(w[i],w[j]));
}
if(a==3){
if(bet(w[i],w[j].a)==0)
z.pb(w[j].a);
if(bet(w[i],w[j].b)==0)
z.pb(w[j].b);
}
}
sort(all(z),[&](cm a,cm b){return norm(a-w[i].a)<norm(b-w[i].a);});
z.erase(unique(all(z),cmeq),z.ed);
rep(j,int(z.size())-1){
int a=idx(z[j]),b=idx(z[j+1]);
g[a].eb(b,m++);
g[b].eb(a,m++);
}
}
struct E{int to;ld cost;};
vvc<E> gg(m+2);
rep(i,s){
for(auto e:g[i]){
for(auto f:g[i]){
gg[e.b^1].pb(E{f.b,abs(turn(pos[e.a],pos[i],pos[f.a]))});
}
}
}
ld sx,sy,tx,ty;
cin>>sx>>sy>>tx>>ty;
int a=idx(cm(sx,sy)),b=idx(cm(tx,ty));
for(auto e:g[a])
gg[m].pb(E{e.b,0});
for(auto e:g[b])
gg[e.b^1].pb(E{m+1,0});
ld ans=dijkstra<E,ld>(gg,m)[m+1]/PI*180;
if(ans>1e9)cout<<-1<<endl;
else cout<<ans<<endl;
}
}
| ### Prompt
Your challenge is to write a cpp solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define int ll
#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=a;i--)
#define per(i,b) gnr(i,0,b)
#define pb push_back
#define eb emplace_back
#define a first
#define b second
#define bg begin()
#define ed end()
#define all(x) x.bg,x.ed
#ifdef LOCAL
#define dmp(x) cerr<<__LINE__<<" "<<#x<<" "<<x<<endl
#else
#define dmp(x) void(0)
#endif
template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(a>b)a=b;}
template<class t> using vc=vector<t>;
template<class t> using vvc=vc<vc<t>>;
using pi=pair<int,int>;
using vi=vc<int>;
template<class t,class u>
ostream& operator<<(ostream& os,const pair<t,u>& p){
return os<<"{"<<p.a<<","<<p.b<<"}";
}
template<class t> ostream& operator<<(ostream& os,const vc<t>& v){
os<<"{";
for(auto e:v)os<<e<<",";
return os<<"}";
}
template<class t> void mkuni(vc<t>&v){
sort(all(v));
v.erase(unique(all(v)),v.ed);
}
using ld=long double;
using cm=complex<ld>;
#define x real()
#define y imag()
const ld eps=1e-8;
const ld PI=acos(ld(-1));
int sgn(ld a){return a<-eps?-1:(a>eps?1:0);}
auto cmcmp=[](const cm&a,const cm&b){
if(sgn(a.x-b.x))return a.x<b.x;
else return sgn(a.y-b.y)<0;
};
auto cmeq=[](const cm&a,const cm&b){
return sgn(a.x-b.x)==0&&sgn(a.y-b.y)==0;
};
ld dot(cm a,cm b){return a.x*b.x+a.y*b.y;}
ld crs(cm a,cm b){return a.x*b.y-a.y*b.x;}
ld crs(cm a,cm b,cm c){return crs(b-a,c-a);}
int ccw(cm a,cm b){return sgn(crs(a,b));}
int ccw(cm a,cm b,cm c){return ccw(b-a,c-a);}
//AOJ1183
int qeq(ld a,ld b,ld c,ld&d,ld&e){
ld f=b*b-4*a*c;
if(sgn(f)<0)return 0;
ld g=sqrt(max(f,ld(0)));
d=(-b+g)/(2*a);
e=(-b-g)/(2*a);
return sgn(f)+1;
}
//(-2)[a,-1](0)[b,1](2)
int bet(cm a,cm b,cm c){
cm d=b-a;
ld e=dot(d,c-a);
if(sgn(e)<=0)return sgn(e)-1;
return sgn(e-norm(d))+1;
}
//AOJ0153
//0-no,1-edge,2-in
int cont(cm a,cm b,cm c,cm d){
if(ccw(a,b,c)==-1)
swap(b,c);
return min({ccw(a,b,d),ccw(b,c,d),ccw(c,a,d)})+1;
}
//AOJ1183
//arg between ab
//assume given lengths are valid
ld arg(ld a,ld b,ld c){
return acos(min(max((a*a+b*b-c*c)/(2*a*b),ld(-1)),ld(1)));
}
//AOJ2233
//a->b->c と進むときに曲がる角度
//a-b-cが一直線上にあれば0が帰る
ld turn(cm a,cm b,cm c){
return arg((c-b)/(b-a));
}
using ln=pair<cm,cm>;
cm dir(ln a){return a.b-a.a;}
cm eval(ln a,ld b){return a.a+dir(a)*b;}
int bet(ln a,cm b){return bet(a.a,a.b,b);}
cm proj(ln a,cm b){
cm c=dir(a);
return a.a+c*dot(c,b-a.a)/norm(c);
}
cm refl(ln a,cm b){
return ld(2)*proj(a,b)-b;
}
//AOJ0153
ld dsp(ln a,cm b){
cm c=proj(a,b);
if(abs(bet(a.a,a.b,c))<=1)return abs(b-c);
return min(abs(b-a.a),abs(b-a.b));
}
int ccw(ln a,cm b){return ccw(a.a,a.b,b);}
//AOJ1157
//0-no,1-yes(endpoint),2-yes(innner),3-overelap
int iss(ln a,ln b){
int c1=ccw(a.a,a.b,b.a),c2=ccw(a.a,a.b,b.b);
int d1=ccw(b.a,b.b,a.a),d2=ccw(b.a,b.b,a.b);
if(c1||c2||d1||d2)return 1-max(c1*c2,d1*d2);
int f=bet(a.a,a.b,b.a),g=bet(a.a,a.b,b.b);
if(max(f,g)==-2||min(f,g)==2)return 0;
return 3;
}
cm cll(ln a,ln b){
return eval(a,crs(b.a,b.b,a.a)/crs(dir(a),dir(b)));
}
//AOJ1157
ld dss(ln a,ln b){
if(iss(a,b))return 0;
return min({dsp(a,b.a),dsp(a,b.b),dsp(b,a.a),dsp(b,a.b)});
}
bool inc(int a,int b,int c){return a<=b&&b<=c;}
template<class E,class D=ll>
vc<D> dijkstra(const vvc<E>& g,int s){
const int n=g.size();
using P=pair<D,int>;
priority_queue<P,vc<P>,greater<P>> pq;
vc<D> dist(n,1e9);
const auto ar=[&](int v,D d){
if(dist[v]>d){
dist[v]=d;
pq.push(P(d,v));
}
};
ar(s,0);
while(pq.size()){
D d;
int v;
tie(d,v)=pq.top();pq.pop();
for(auto e:g[v])
ar(e.to,d+e.cost);
}
return dist;
}
signed main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout<<fixed<<setprecision(20);
while(1){
int n;cin>>n;
if(n==0)break;
vc<ln> w;
rep(i,n){
ld a,b,c,d;
cin>>a>>b>>c>>d;
w.eb(cm(a,b),cm(c,d));
}
vc<cm> pos;
rep(i,n){
pos.pb(w[i].a);
pos.pb(w[i].b);
}
rep(i,n)rep(j,i){
if(inc(1,iss(w[i],w[j]),2))
pos.pb(cll(w[i],w[j]));
}
sort(all(pos),cmcmp);
pos.erase(unique(all(pos),cmeq),pos.ed);
const auto idx=[&](cm a){
return lower_bound(all(pos),a,cmcmp)-pos.bg;
};
int s=pos.size();
vvc<pi> g(s);
int m=0;
rep(i,n){
vc<cm> z{w[i].a,w[i].b};
rep(j,n)if(i!=j){
int a=iss(w[i],w[j]);
if(a==1||a==2){
z.pb(cll(w[i],w[j]));
}
if(a==3){
if(bet(w[i],w[j].a)==0)
z.pb(w[j].a);
if(bet(w[i],w[j].b)==0)
z.pb(w[j].b);
}
}
sort(all(z),[&](cm a,cm b){return norm(a-w[i].a)<norm(b-w[i].a);});
z.erase(unique(all(z),cmeq),z.ed);
rep(j,int(z.size())-1){
int a=idx(z[j]),b=idx(z[j+1]);
g[a].eb(b,m++);
g[b].eb(a,m++);
}
}
struct E{int to;ld cost;};
vvc<E> gg(m+2);
rep(i,s){
for(auto e:g[i]){
for(auto f:g[i]){
gg[e.b^1].pb(E{f.b,abs(turn(pos[e.a],pos[i],pos[f.a]))});
}
}
}
ld sx,sy,tx,ty;
cin>>sx>>sy>>tx>>ty;
int a=idx(cm(sx,sy)),b=idx(cm(tx,ty));
for(auto e:g[a])
gg[m].pb(E{e.b,0});
for(auto e:g[b])
gg[e.b^1].pb(E{m+1,0});
ld ans=dijkstra<E,ld>(gg,m)[m+1]/PI*180;
if(ans>1e9)cout<<-1<<endl;
else cout<<ans<<endl;
}
}
``` |
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <tuple>
#include <vector>
using namespace std;
constexpr double EPS = 1e-9;
struct point {
double x, y;
explicit point(double x_ = 0.0, double y_ = 0.0):x(x_), y(y_) {}
point(const point &p):x(p.x), y(p.y) {}
point operator+ (const point &p) const {
return point(x + p.x, y + p.y);
}
point operator- (const point &p) const {
return point(x - p.x, y - p.y);
}
point operator* (double s) const {
return point(x * s, y * s);
}
point operator* (const point &p) const {
return point(x * p.x - y * p.y, x * p.y + y * p.x);
}
point operator/ (double s) const {
return point(x / s, y / s);
}
bool operator< (const point &p) const {
return x + EPS < p.x || (abs(x - p.x) < EPS && y + EPS < p.y);
}
bool operator== (const point &p) const {
return abs(x - p.x) < EPS && abs(y - p.y) < EPS;
}
};
double angle(const point &p) {
return atan2(p.y, p.x);
}
double norm(const point &p) {
return p.x * p.x + p.y * p.y;
}
double abs(const point &p) {
return sqrt(norm(p));
}
double dot(const point &a, const point &b) {
return a.x * b.x + a.y * b.y;
}
double cross(const point &a, const point &b) {
return a.x * b.y - a.y * b.x;
}
struct segment {
point a, b;
segment(const point &a_, const point &b_):a(a_), b(b_){}
};
int ccw(const point &a, point b, point c) {
b = b - a;
c = c - a;
const double tmp = cross(b, c);
if(tmp > EPS) return 1; // ccw
if(tmp < -EPS) return -1; // cw
if(dot(b, c) < 0) return 2; // c, a, b 順に一直線上
if(norm(b) < norm(c)) return -2; // a, b, c 順に一直線上
return 0; //a, c, b 順で一直線上
}
bool intersect(const segment &s, const segment &t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0
&& ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
bool intersect(const segment &s, const point &p) {
return ccw(s.a, s.b, p) == 0;
}
// 先にintersectで交差判定をすること
point crosspoint(const segment &s, const segment &t) {
const double tmp = cross(s.b - s.a, t.b - t.a);
if(abs(tmp) < EPS) { // 一直線上
if(intersect(s, t.a)) return t.a;
if(intersect(s, t.b)) return t.b;
if(intersect(t, s.a)) return s.a;
return s.b;
}
return t.a + (t.b - t.a) * (cross(s.b - s.a, s.b - t.a) / tmp);
}
struct edge {
int to;
double cost, theta;
int rev;
edge(int to_, double cost_, double theta_, int rev_):to(to_), cost(cost_), theta(theta_), rev(rev_) {}
};
typedef vector<vector<edge>> graph;
graph arrangement(const vector<segment> &segments, vector<point> &points) {
const int n = segments.size();
points.clear();
for(int i = 0; i < n; ++i) {
const auto &s1 = segments[i];
points.emplace_back(s1.a);
points.emplace_back(s1.b);
for(int j = i + 1; j < n; ++j) {
const auto &s2 = segments[j];
if(intersect(s1, s2)) {
points.emplace_back(crosspoint(s1, s2));
}
}
}
sort(points.begin(), points.end());
points.erase(unique(points.begin(), points.end()), points.end());
const int V = points.size();
graph G(V);
for(const auto &s : segments) {
vector<pair<double, int>> vs;
for(int i = 0; i < V; ++i) {
if(intersect(s, points[i])) {
vs.emplace_back(abs(s.a - points[i]), i);
}
}
sort(vs.begin(), vs.end());
for(int i = 1; i < static_cast<int>(vs.size()); ++i) {
const int v = vs[i].second;
const int u = vs[i - 1].second;
const double d = vs[i].first - vs[i - 1].first;
G[v].emplace_back(u, d, angle(points[u] - points[v]) * 180.0 / M_PI, G[u].size());
G[u].emplace_back(v, d, angle(points[v] - points[u]) * 180.0 / M_PI, G[v].size() - 1);
}
}
return G;
}
typedef tuple<double, int, int> state; // dist, v, from edge
double dijkstra(int s, int g, const graph &G) {
const int n = G.size();
if(s >= n || g >= n) return -1;
if(s == g) return 0;
vector<map<int, double>> dist(n);
priority_queue<state, vector<state>, greater<state>> que;
for(const auto &e : G[s]) {
dist[e.to][e.rev] = 0.0;
que.push(state(0.0, e.to, e.rev));
}
while(!que.empty()) {
int v, from;
double d;
tie(d, v, from) = que.top();
que.pop();
if(dist[v][from] + EPS < d) continue;
if(v == g) return d;
const double current_angle = G[v][from].theta - 180.0;
for(const auto &e : G[v]) {
double diff_angle = e.theta - current_angle;
if(diff_angle > 180.0) diff_angle -= 360.0;
const double next_dist = d + abs(diff_angle);
if(!dist[e.to].count(e.rev) || dist[e.to][e.rev] > next_dist + EPS) {
dist[e.to][e.rev] = next_dist;
que.push(state(next_dist, e.to, e.rev));
}
}
}
return -1;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(10);
for(int n; cin >> n && n;) {
vector<segment> segments;
segments.reserve(n);
for(int i = 0; i < n; ++i) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
segments.emplace_back(point(x1, y1), point(x2, y2));
}
vector<point> points;
const graph G = arrangement(segments, points);
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
const int s = lower_bound(points.begin(), points.end(), point(sx, sy)) - points.begin();
const int g = lower_bound(points.begin(), points.end(), point(gx, gy)) - points.begin();
const double ans = dijkstra(s, g, G);
if(ans < 0) {
cout << "-1" << endl;
}
else {
cout << ans << endl;
}
}
return EXIT_SUCCESS;
} | ### Prompt
Please formulate a CPP solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <tuple>
#include <vector>
using namespace std;
constexpr double EPS = 1e-9;
struct point {
double x, y;
explicit point(double x_ = 0.0, double y_ = 0.0):x(x_), y(y_) {}
point(const point &p):x(p.x), y(p.y) {}
point operator+ (const point &p) const {
return point(x + p.x, y + p.y);
}
point operator- (const point &p) const {
return point(x - p.x, y - p.y);
}
point operator* (double s) const {
return point(x * s, y * s);
}
point operator* (const point &p) const {
return point(x * p.x - y * p.y, x * p.y + y * p.x);
}
point operator/ (double s) const {
return point(x / s, y / s);
}
bool operator< (const point &p) const {
return x + EPS < p.x || (abs(x - p.x) < EPS && y + EPS < p.y);
}
bool operator== (const point &p) const {
return abs(x - p.x) < EPS && abs(y - p.y) < EPS;
}
};
double angle(const point &p) {
return atan2(p.y, p.x);
}
double norm(const point &p) {
return p.x * p.x + p.y * p.y;
}
double abs(const point &p) {
return sqrt(norm(p));
}
double dot(const point &a, const point &b) {
return a.x * b.x + a.y * b.y;
}
double cross(const point &a, const point &b) {
return a.x * b.y - a.y * b.x;
}
struct segment {
point a, b;
segment(const point &a_, const point &b_):a(a_), b(b_){}
};
int ccw(const point &a, point b, point c) {
b = b - a;
c = c - a;
const double tmp = cross(b, c);
if(tmp > EPS) return 1; // ccw
if(tmp < -EPS) return -1; // cw
if(dot(b, c) < 0) return 2; // c, a, b 順に一直線上
if(norm(b) < norm(c)) return -2; // a, b, c 順に一直線上
return 0; //a, c, b 順で一直線上
}
bool intersect(const segment &s, const segment &t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0
&& ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
bool intersect(const segment &s, const point &p) {
return ccw(s.a, s.b, p) == 0;
}
// 先にintersectで交差判定をすること
point crosspoint(const segment &s, const segment &t) {
const double tmp = cross(s.b - s.a, t.b - t.a);
if(abs(tmp) < EPS) { // 一直線上
if(intersect(s, t.a)) return t.a;
if(intersect(s, t.b)) return t.b;
if(intersect(t, s.a)) return s.a;
return s.b;
}
return t.a + (t.b - t.a) * (cross(s.b - s.a, s.b - t.a) / tmp);
}
struct edge {
int to;
double cost, theta;
int rev;
edge(int to_, double cost_, double theta_, int rev_):to(to_), cost(cost_), theta(theta_), rev(rev_) {}
};
typedef vector<vector<edge>> graph;
graph arrangement(const vector<segment> &segments, vector<point> &points) {
const int n = segments.size();
points.clear();
for(int i = 0; i < n; ++i) {
const auto &s1 = segments[i];
points.emplace_back(s1.a);
points.emplace_back(s1.b);
for(int j = i + 1; j < n; ++j) {
const auto &s2 = segments[j];
if(intersect(s1, s2)) {
points.emplace_back(crosspoint(s1, s2));
}
}
}
sort(points.begin(), points.end());
points.erase(unique(points.begin(), points.end()), points.end());
const int V = points.size();
graph G(V);
for(const auto &s : segments) {
vector<pair<double, int>> vs;
for(int i = 0; i < V; ++i) {
if(intersect(s, points[i])) {
vs.emplace_back(abs(s.a - points[i]), i);
}
}
sort(vs.begin(), vs.end());
for(int i = 1; i < static_cast<int>(vs.size()); ++i) {
const int v = vs[i].second;
const int u = vs[i - 1].second;
const double d = vs[i].first - vs[i - 1].first;
G[v].emplace_back(u, d, angle(points[u] - points[v]) * 180.0 / M_PI, G[u].size());
G[u].emplace_back(v, d, angle(points[v] - points[u]) * 180.0 / M_PI, G[v].size() - 1);
}
}
return G;
}
typedef tuple<double, int, int> state; // dist, v, from edge
double dijkstra(int s, int g, const graph &G) {
const int n = G.size();
if(s >= n || g >= n) return -1;
if(s == g) return 0;
vector<map<int, double>> dist(n);
priority_queue<state, vector<state>, greater<state>> que;
for(const auto &e : G[s]) {
dist[e.to][e.rev] = 0.0;
que.push(state(0.0, e.to, e.rev));
}
while(!que.empty()) {
int v, from;
double d;
tie(d, v, from) = que.top();
que.pop();
if(dist[v][from] + EPS < d) continue;
if(v == g) return d;
const double current_angle = G[v][from].theta - 180.0;
for(const auto &e : G[v]) {
double diff_angle = e.theta - current_angle;
if(diff_angle > 180.0) diff_angle -= 360.0;
const double next_dist = d + abs(diff_angle);
if(!dist[e.to].count(e.rev) || dist[e.to][e.rev] > next_dist + EPS) {
dist[e.to][e.rev] = next_dist;
que.push(state(next_dist, e.to, e.rev));
}
}
}
return -1;
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout.setf(ios::fixed);
cout.precision(10);
for(int n; cin >> n && n;) {
vector<segment> segments;
segments.reserve(n);
for(int i = 0; i < n; ++i) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
segments.emplace_back(point(x1, y1), point(x2, y2));
}
vector<point> points;
const graph G = arrangement(segments, points);
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
const int s = lower_bound(points.begin(), points.end(), point(sx, sy)) - points.begin();
const int g = lower_bound(points.begin(), points.end(), point(gx, gy)) - points.begin();
const double ans = dijkstra(s, g, G);
if(ans < 0) {
cout << "-1" << endl;
}
else {
cout << ans << endl;
}
}
return EXIT_SUCCESS;
}
``` |
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
//merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
/*
if(s == g) {
cout << 0 << endl;
continue;
}
*/
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
} | ### Prompt
Please formulate a CPP solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
//merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
/*
if(s == g) {
cout << 0 << endl;
continue;
}
*/
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
}
``` |
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
/*
if(s == g) {
cout << 0 << endl;
continue;
}
*/
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) if(u != w) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
} | ### Prompt
Develop a solution in CPP to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
/*
if(s == g) {
cout << 0 << endl;
continue;
}
*/
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) if(u != w) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
}
``` |
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps = 1e-9;
/* ??????????????¬ */
#include <complex>
typedef complex<ld> Point;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define all(x) (x).begin(),(x).end()
const ld pi = acos(-1.0);
const ld dtop = pi / 180.;
const ld ptod = 1. / dtop;
namespace std {
bool operator<(const Point &lhs, const Point &rhs) {
if (lhs.real() < rhs.real() - eps) return true;
if (lhs.real() > rhs.real() + eps) return false;
return lhs.imag() < rhs.imag();
}
}
// ????????\???
Point input_Point() {
ld x, y;
cin >> x >> y;
return Point(x, y);
}
// ????????????????????????
bool eq(const ld a, const ld b) {
return (abs(a - b) < eps);
}
// ??????
ld dot(const Point& a, const Point& b) {
return real(conj(a) * b);
}
// ??????
ld cross(const Point& a, const Point& b) {
return imag(conj(a) * b);
}
// ??´????????????
class Line {
public:
Point a, b;
Line() : a(Point(0, 0)), b(Point(0, 0)) {}
Line(Point a, Point b) : a(a), b(b) {}
Point operator[](const int _num)const {
if (_num == 0)return a;
else if (_num == 1)return b;
else {
assert(false);
return Point();
}
}
};
// ????????????
class Circle {
public:
Point p;
ld r;
Circle() : p(Point(0, 0)), r(0) {}
Circle(Point p, ld r) : p(p), r(r) {}
};
// ccw
// 1: a,b,c??????????¨???¨?????????????????¶
//-1: a,b,c???????¨???¨?????????????????¶
// 2: c,a,b???????????´???????????¶
//-2: a,b,c???????????´???????????¶
// 0: a,c,b???????????´???????????¶
int ccw(const Point& a, const Point &b, const Point &c) {
const Point nb(b - a);
const Point nc(c - a);
if (cross(nb, nc) > eps) return 1; // a,b,c??????????¨???¨?????????????????¶
if (cross(nb, nc) < -eps) return -1; // a,b,c???????¨???¨?????????????????¶
if (dot(nb, nc) < 0) return 2; // c,a,b???????????´???????????¶
if (norm(nb) < norm(nc)) return -2; // a,b,c???????????´???????????¶
return 0; // a,c,b???????????´???????????¶
}
/* ???????????? */
// ??´?????¨??´??????????????????
bool isis_ll(const Line& l, const Line& m) {
return !eq(cross(l.b - l.a, m.b - m.a), 0);
}
// ??´?????¨?????????????????????
bool isis_ls(const Line& l, const Line& s) {
return isis_ll(l, s) &&
(cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < eps);
}
// ????????¨?????????????????????
bool isis_ss(const Line& s, const Line& t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&
ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
// ????????´????????????
bool isis_lp(const Line& l, const Point& p) {
return (abs(cross(l.b - p, l.a - p)) < eps);
}
// ?????????????????????
bool isis_sp(const Line& s, const Point& p) {
return (abs(s.a - p) + abs(s.b - p) - abs(s.b - s.a) < eps);
}
// ??????????¶?
Point proj(const Line &l, const Point& p) {
ld t = dot(p - l.a, l.b - l.a) / norm(l.a - l.b);
return l.a + t * (l.b - l.a);
}
//???????±??????????????????????
Point reflect(const Line &l, const Point &p) {
Point pr = proj(l, p);
return pr * 2.l - p;
}
// ??´?????¨??´????????????
Point is_ll(const Line &s, const Line& t) {
Point sv = s.b - s.a, tv = t.b - t.a;
assert(cross(sv, tv) != 0);
return s.a + sv * cross(tv, t.a - s.a) / cross(tv, sv);
}
// ??´?????¨??´????????????
vector<Point> is_ll2(const Line &s, const Line& t) {
Point sv = s.b - s.a, tv = t.b - t.a;
if (cross(sv, tv) != 0)return vector<Point>(1, is_ll(s, t));
else {
vector<Point>ans;
for (int k = 0; k < 2; ++k) {
if (isis_sp(s, t[k]) && find(ans.begin(), ans.end(), t[k]) == ans.end())ans.push_back(t[k]);
if (isis_sp(t, s[k]) && find(ans.begin(), ans.end(), s[k]) == ans.end())ans.push_back(s[k]);
}
return ans;
}
}
// ????????¨???????????????
//???????????£????????¨???????????¨assert(false)
Point is_ss(const Line &s, const Line& t) {
if (isis_ss(s, t)) {
for (int k = 0; k < 2; ++k) {
for (int l = 0; l < 2; ++l) {
if (s[k] == t[l])return s[k];
}
}
return is_ll(s, t);
}
else {
//??????isis_ss?????????
assert(false);
return Point(0, 0);
}
}
// ????????¨???????????????
vector<Point> is_ss2(const Line &s, const Line& t) {
vector<Point> kouho(is_ll2(s, t));
vector<Point>ans;
for (auto p : kouho) {
if (isis_sp(s, p) && isis_sp(t, p))ans.emplace_back(p);
}
return ans;
}
// ??´?????¨???????????¢
ld dist_lp(const Line& l, const Point& p) {
return abs(p - proj(l, p));
}
//??´?????¨??´???????????¢
ld dist_ll(const Line& l, const Line& m) {
return isis_ll(l, m) ? 0 : dist_lp(l, m.a);
}
// ??´?????¨??????????????¢
ld dist_ls(const Line& l, const Line& s) {
return isis_ls(l, s) ? 0 : min(dist_lp(l, s.a), dist_lp(l, s.b));
}
// ????????¨???????????¢
ld dist_sp(const Line& s, const Point& p) {
Point r = proj(s, p);
return isis_sp(s, r) ? abs(r - p) : min(abs(s.a - p), abs(s.b - p));
}
// ????????¨??????????????¢
ld dist_ss(const Line& s, const Line& t) {
if (isis_ss(s, t)) return 0;
return min({ dist_sp(s, t.a), dist_sp(s, t.b), dist_sp(t, s.a), dist_sp(t, s.b) });
}
//??´?????¨??´?????????????????????????????????
Line bisection(const Line &s, const Line &t) {
const Point laglanju(is_ll(s, t));
const Point avec = !(abs(laglanju - s[0])<eps) ? s[0] - laglanju : s[1] - laglanju;
const Point bvec = !(abs(laglanju - t[0])<eps) ? t[0] - laglanju : t[1] - laglanju;
return Line(laglanju, laglanju + (abs(bvec)*avec + abs(avec)*bvec) / (abs(avec) + abs(bvec)));
}
//???????????´?????????????????????
//???????????´??????????????§???????????¨????¢?????????¨?????????
Point inner_center(const vector<Line>&ls) {
vector<Point>vertics;
for (int i = 0; i <static_cast<int>(ls.size()); ++i) {
vertics.push_back(is_ll(ls[i], ls[(i + 1) % 3]));
}
if (vertics[0] == vertics[1] || vertics[1] == vertics[2] || vertics[2] == vertics[0])return vertics[0];
Line bi1(bisection(Line(vertics[0], vertics[1]), Line(vertics[0], vertics[2])));
Line bi2(bisection(Line(vertics[1], vertics[2]), Line(vertics[1], vertics[0])));
if (bi1[0] == bi2[0])return bi1[0];
else {
return is_ll(bi1, bi2);
}
}
//???????????´?????????????????????
//???????????´??????????????§???????????¨????¢?????????¨?????????
vector<Point> ex_center(const vector<Line>&ls) {
vector<Point>vertics;
for (int i = 0; i < static_cast<int>(ls.size()); ++i) {
vertics.push_back(is_ll(ls[i], ls[(i + 1) % 3]));
}
if (abs(vertics[0] - vertics[1])<eps || abs(vertics[1] - vertics[2])<eps || (abs(vertics[2] - vertics[0])<eps))return vector<Point>();
vector<Point>ecs;
for (int i = 0; i < 3; ++i) {
Line bi1(bisection(Line(vertics[i], vertics[i] * 2.0l - vertics[(i + 2) % 3]), Line(vertics[i], vertics[(i + 1) % 3])));
Line bi2(bisection(Line(vertics[(i + 1) % 3], vertics[(i + 1) % 3] * 2.0l - vertics[(i + 2) % 3]), Line(vertics[(i + 1) % 3], vertics[i])));
ecs.push_back(is_ll(bi1, bi2));
}
return ecs;
}
//a,b:??????
//c:????????§??????
//???????????´?????????????????¢?????????????±??????????
vector<Point> same_dis(const vector<Line>&ls) {
vector<Point>vertics;
vertics.push_back(is_ll(ls[0], ls[2]));
vertics.push_back(is_ll(ls[1], ls[2]));
if (abs(vertics[0] - vertics[1]) < eps)return vector<Point>{vertics[0]};
Line bis(bisection(ls[0], ls[1]));
vector<Point>ecs;
Line abi(bisection(Line(vertics[0], vertics[1]), ls[0]));
ecs.push_back(is_ll(bis, abi));
Line bbi(bisection(Line(vertics[0], 2.l*vertics[0] - vertics[1]), ls[0]));
ecs.push_back(is_ll(bis, bbi));
return ecs;
}
/* ??? */
// ?????¨????????????
vector<Point> is_cc(const Circle& c1, const Circle& c2) {
vector<Point> res;
ld d = abs(c1.p - c2.p);
ld rc = (d * d + c1.r * c1.r - c2.r * c2.r) / (2 * d);
ld dfr = c1.r * c1.r - rc * rc;
if (abs(dfr) < eps) dfr = 0.0;
else if (dfr < 0.0) return res; // no intersection
ld rs = sqrt(dfr);
Point diff = (c2.p - c1.p) / d;
res.push_back(c1.p + diff * Point(rc, rs));
if (dfr != 0.0) res.push_back(c1.p + diff * Point(rc, -rs));
return res;
}
//???????????????????????????
/* 0 => out
1 => on
2 => in*/
int is_in_Circle(const Circle &cir, const Point& p) {
ld dis = abs(cir.p - p);
if (dis > cir.r + eps)return 0;
else if (dis < cir.r - eps)return 2;
else return 1;
}
//???lc??????rc??????????????????
/*0 => out
1 => on
2 => in*/
int Circle_in_Circle(const Circle &lc, const Circle&rc) {
ld dis = abs(lc.p - rc.p);
if (dis < rc.r - lc.r - eps)return 2;
else if (dis>rc.r - lc.r + eps)return 0;
else return 1;
}
// ?????¨??´????????????
vector<Point> is_lc(const Circle& c, const Line& l) {
vector<Point> res;
ld d = dist_lp(l, c.p);
if (d < c.r + eps) {
ld len = (d > c.r) ? 0.0 : sqrt(c.r * c.r - d * d); //safety;
Point nor = (l.a - l.b) / abs(l.a - l.b);
res.push_back(proj(l, c.p) + len * nor);
res.push_back(proj(l, c.p) - len * nor);
}
return res;
}
// ?????¨??????????????¢
vector<Point> is_sc(const Circle& c, const Line& l) {
vector<Point> v = is_lc(c, l), res;
for (Point p : v)
if (isis_sp(l, p)) res.push_back(p);
return res;
}
// ?????¨????????\???
vector<Line> tangent_cp(const Circle& c, const Point& p) {
vector<Line> ret;
Point v = c.p - p;
ld d = abs(v);
ld l = sqrt(norm(v) - c.r * c.r);
if (isnan(l)) { return ret; }
Point v1 = v * Point(l / d, c.r / d);
Point v2 = v * Point(l / d, -c.r / d);
ret.push_back(Line(p, p + v1));
if (l < eps) return ret;
ret.push_back(Line(p, p + v2));
return ret;
}
// ?????¨????????\???
vector<Line> tangent_cc(const Circle& c1, const Circle& c2) {
vector<Line> ret;
if (abs(c1.p - c2.p) - (c1.r + c2.r) > -eps) {
Point center = (c1.p * c2.r + c2.p * c1.r) / (c1.r + c2.r);
ret = tangent_cp(c1, center);
}
if (abs(c1.r - c2.r) > eps) {
Point out = (-c1.p * c2.r + c2.p * c1.r) / (c1.r - c2.r);
vector<Line> nret = tangent_cp(c1, out);
ret.insert(ret.end(), all(nret));
}
else {
Point v = c2.p - c1.p;
v /= abs(v);
Point q1 = c1.p + v * Point(0, 1) * c1.r;
Point q2 = c1.p + v * Point(0, -1) * c1.r;
ret.push_back(Line(q1, q1 + v));
ret.push_back(Line(q2, q2 + v));
}
return ret;
}
//??????????????????????????¢???
ld two_Circle_area(const Circle&l, const Circle&r) {
ld dis = abs(l.p - r.p);
if (dis > l.r + r.r)return 0;
else if (dis + r.r < l.r) {
return r.r*r.r*pi;
}
else if (dis + l.r < r.r) {
return l.r*l.r*pi;
}
else {
ld ans = (l.r)*(l.r)*acos((dis*dis + l.r*l.r - r.r*r.r) / (2 * dis*l.r)) +
(r.r)*(r.r)*acos((dis*dis + r.r*r.r - l.r*l.r) / (2 * dis*r.r)) -
sqrt(4 * dis*dis*l.r*l.r - (dis*dis + l.r*l.r - r.r*r.r)*(dis*dis + l.r*l.r - r.r*r.r)) / 2;
return ans;
}
}
/* ????§???¢ */
typedef vector<Point> Polygon;
// ??¢???
ld area(const Polygon &p) {
ld res = 0;
int n = p.size();
rep(j, n) res += cross(p[j], p[(j + 1) % n]);
return res / 2;
}
//????§???¢????????¢??????
bool is_counter_clockwise(const Polygon &poly) {
ld angle = 0;
int n = poly.size();
rep(i, n) {
Point a = poly[i], b = poly[(i + 1) % n], c = poly[(i + 2) % n];
angle += arg((c - b) / (b - a));
}
return angle > eps;
}
// ??????????????????
/*0 => out
1 => on
2 => in*/
int is_in_Polygon(const Polygon &poly, const Point& p) {
ld angle = 0;
int n = poly.size();
rep(i, n) {
Point a = poly[i], b = poly[(i + 1) % n];
if (isis_sp(Line(a, b), p)) return 1;
angle += arg((b - p) / (a - p));
}
return eq(angle, 0) ? 0 : 2;
}
//??????????????????2?????????
enum { out, on, in };
int convex_contains(const Polygon &P, const Point &p) {
const int n = P.size();
Point g = (P[0] + P[n / 3] + P[2 * n / 3]) / 3.0l; // inner-point
int a = 0, b = n;
while (a + 1 < b) { // invariant: c is in fan g-P[a]-P[b]
int c = (a + b) / 2;
if (cross(P[a] - g, P[c] - g) > 0) { // angle < 180 deg
if (cross(P[a] - g, p - g) > 0 && cross(P[c] - g, p - g) < 0) b = c;
else a = c;
}
else {
if (cross(P[a] - g, p - g) < 0 && cross(P[c] - g, p - g) > 0) a = c;
else b = c;
}
}
b %= n;
if (cross(P[a] - p, P[b] - p) < 0) return 0;
if (cross(P[a] - p, P[b] - p) > 0) return 2;
return 1;
}
// ??????
//???????????????????????¨????????????????????§??¨???
Polygon convex_hull(vector<Point> ps) {
int n = ps.size();
int k = 0;
sort(ps.begin(), ps.end());
Polygon ch(2 * n);
for (int i = 0; i < n; ch[k++] = ps[i++])
while (k >= 2 && ccw(ch[k - 2], ch[k - 1], ps[i]) <= 0) --k;
for (int i = n - 2, t = k + 1; i >= 0; ch[k++] = ps[i--])
while (k >= t && ccw(ch[k - 2], ch[k - 1], ps[i]) <= 0) --k;
ch.resize(k - 1);
return ch;
}
//????????????
vector<Polygon> convex_cut(const Polygon &ps, const Line& l) {
int n = ps.size();
Polygon q;
Polygon r;
rep(i, n) {
Point a = ps[i], b = ps[(i + 1) % n];
Line m = Line(a, b);
if (ccw(l.a, l.b, a) != -1) q.push_back(a);
if (ccw(l.a, l.b, a) != 1) r.push_back(a);
if (ccw(l.a, l.b, a) * ccw(l.a, l.b, b) < 0 && isis_ll(l, m)) {
q.push_back(is_ll(l, m));
r.push_back(is_ll(l, m));
}
}
const vector<Polygon>polys{ q,r };
return polys;
}
/* ??¢??¬??????????????? */
void add_Point(vector<Point> &ps, const Point p) {
for (Point q : ps) if (abs(q - p) < eps) return;
ps.push_back(p);
}
typedef ld Weight;
struct edge {
int id;
int src, dst;
Weight kaku;
edge(int id_,int src, int dst, Weight weight) :
id(id_),src(src), dst(dst), kaku(weight) { }
};
typedef vector<edge> edges;
typedef vector<edges> graph;
void add_edge(graph &g, const int id,const int from, const int to, const Weight& weight) {
g[from].push_back(edge{ id,from, to, weight });
}
graph segment_arrangement(const vector<Line> &s, const vector<Point> &p) {
int n = p.size(), m = s.size();
graph g(n);
int aid = 0;
rep(i, m) {
vector<pair<ld, int>> vec;
rep(j, n) if (isis_sp(s[i], p[j]))
vec.emplace_back(abs(s[i].a - p[j]), j);
sort(all(vec));
rep(j, vec.size() - 1) {
int from = vec[j].second, to = vec[j + 1].second;
{
ld theta = dot(p[to] - p[from], Point(1, 0)) / abs(p[to] - p[from]);
ld kaku =(p[to]-p[from]).imag() > 0 ? acos(theta) : -acos(theta);
add_edge(g, aid++, from, to, kaku);
}
{
ld theta = dot(p[from] - p[to], Point(1, 0)) / abs(p[to] - p[from]);
ld kaku = (p[from] - p[to]).imag() > 0 ? acos(theta) : -acos(theta);
add_edge(g, aid++, to, from, kaku);
}
}
}
return g;
}
Point start, goal;
vector<int>ss, gs;
vector<Point>crss;
graph sennbunn_arrangement(const vector<Line>&s) {
for (int i = 0; i < static_cast<int>(s.size()); ++i) {
for (int j = i + 1; j < static_cast<int>(s.size()); ++j) {
if (isis_ss(s[i], s[j])) {
crss.push_back(is_ll2(s[i], s[j])[0]);
}
}
}
for (int i = 0; i <static_cast<int>(s.size()); ++i) {
crss.push_back(s[i][0]);
crss.push_back(s[i][1]);
}
sort(crss.begin(), crss.end());
crss.erase(unique(crss.begin(), crss.end()), crss.end());
for (int i = 0; i < crss.size(); ++i) {
if (crss[i] == start) {
ss.push_back(i);
}
else if (crss[i] == goal) {
gs.push_back(i);
}
}
return segment_arrangement(s, crss);
}
struct aa {
edge e;
bool isstart;
ld time;
};
class Compare {
public:
//aa?????????????????¶
bool operator()(const aa&l, const aa&r) {
return l.time> r.time;
}
};
int main() {
while (1) {
ss.clear();
gs.clear();
crss.clear();
int N; cin >> N;
if (!N)break;
vector<Line>ls;
for (int i = 0; i < N; ++i) {
int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;
Line l(Point(x1, y1), Point(x2, y2));
ls.emplace_back(l);
}
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
start = Point(sx, sy);
goal = Point(gx, gy);
graph g(sennbunn_arrangement(ls));
/*vector<edge>id_edges(10000);
for (auto es : g) {
for (auto e : es) {
id_edges[e.id] = e;
}
}*/
priority_queue<aa, vector<aa>, Compare>que;
int num = 9000;
for (auto s : ss) {
que.push(aa{ edge(num++ , -1, s, -1), true, 0 });
}
ld ans = -1;
vector<ld>memo(10000, 1e18);
while (!que.empty()) {
auto atop(que.top());
que.pop();
const int aid = atop.e.id;
const int asrc = atop.e.dst;
const ld atime = atop.time;
const ld akaku = atop.e.kaku;
if (find(gs.begin(), gs.end(), asrc) != gs.end()) {
ans = atime;
break;
}
for (auto e : g[asrc]) {
ld needkaku = min(abs(akaku - e.kaku), 2 * pi - abs(akaku - e.kaku));
ld sum = atime+ needkaku;
if (atop.isstart)sum = 0;
if (memo[e.id] > sum) {
memo[e.id] = sum;
que.push(aa{ e,false,sum });
}
}
}
if (ans < 0)cout << -1 << endl;
else cout << setprecision(12)<<fixed<<ans/pi*180 << endl;
}
return 0;
} | ### Prompt
Please formulate a cpp solution to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps = 1e-9;
/* ??????????????¬ */
#include <complex>
typedef complex<ld> Point;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define all(x) (x).begin(),(x).end()
const ld pi = acos(-1.0);
const ld dtop = pi / 180.;
const ld ptod = 1. / dtop;
namespace std {
bool operator<(const Point &lhs, const Point &rhs) {
if (lhs.real() < rhs.real() - eps) return true;
if (lhs.real() > rhs.real() + eps) return false;
return lhs.imag() < rhs.imag();
}
}
// ????????\???
Point input_Point() {
ld x, y;
cin >> x >> y;
return Point(x, y);
}
// ????????????????????????
bool eq(const ld a, const ld b) {
return (abs(a - b) < eps);
}
// ??????
ld dot(const Point& a, const Point& b) {
return real(conj(a) * b);
}
// ??????
ld cross(const Point& a, const Point& b) {
return imag(conj(a) * b);
}
// ??´????????????
class Line {
public:
Point a, b;
Line() : a(Point(0, 0)), b(Point(0, 0)) {}
Line(Point a, Point b) : a(a), b(b) {}
Point operator[](const int _num)const {
if (_num == 0)return a;
else if (_num == 1)return b;
else {
assert(false);
return Point();
}
}
};
// ????????????
class Circle {
public:
Point p;
ld r;
Circle() : p(Point(0, 0)), r(0) {}
Circle(Point p, ld r) : p(p), r(r) {}
};
// ccw
// 1: a,b,c??????????¨???¨?????????????????¶
//-1: a,b,c???????¨???¨?????????????????¶
// 2: c,a,b???????????´???????????¶
//-2: a,b,c???????????´???????????¶
// 0: a,c,b???????????´???????????¶
int ccw(const Point& a, const Point &b, const Point &c) {
const Point nb(b - a);
const Point nc(c - a);
if (cross(nb, nc) > eps) return 1; // a,b,c??????????¨???¨?????????????????¶
if (cross(nb, nc) < -eps) return -1; // a,b,c???????¨???¨?????????????????¶
if (dot(nb, nc) < 0) return 2; // c,a,b???????????´???????????¶
if (norm(nb) < norm(nc)) return -2; // a,b,c???????????´???????????¶
return 0; // a,c,b???????????´???????????¶
}
/* ???????????? */
// ??´?????¨??´??????????????????
bool isis_ll(const Line& l, const Line& m) {
return !eq(cross(l.b - l.a, m.b - m.a), 0);
}
// ??´?????¨?????????????????????
bool isis_ls(const Line& l, const Line& s) {
return isis_ll(l, s) &&
(cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < eps);
}
// ????????¨?????????????????????
bool isis_ss(const Line& s, const Line& t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 &&
ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
// ????????´????????????
bool isis_lp(const Line& l, const Point& p) {
return (abs(cross(l.b - p, l.a - p)) < eps);
}
// ?????????????????????
bool isis_sp(const Line& s, const Point& p) {
return (abs(s.a - p) + abs(s.b - p) - abs(s.b - s.a) < eps);
}
// ??????????¶?
Point proj(const Line &l, const Point& p) {
ld t = dot(p - l.a, l.b - l.a) / norm(l.a - l.b);
return l.a + t * (l.b - l.a);
}
//???????±??????????????????????
Point reflect(const Line &l, const Point &p) {
Point pr = proj(l, p);
return pr * 2.l - p;
}
// ??´?????¨??´????????????
Point is_ll(const Line &s, const Line& t) {
Point sv = s.b - s.a, tv = t.b - t.a;
assert(cross(sv, tv) != 0);
return s.a + sv * cross(tv, t.a - s.a) / cross(tv, sv);
}
// ??´?????¨??´????????????
vector<Point> is_ll2(const Line &s, const Line& t) {
Point sv = s.b - s.a, tv = t.b - t.a;
if (cross(sv, tv) != 0)return vector<Point>(1, is_ll(s, t));
else {
vector<Point>ans;
for (int k = 0; k < 2; ++k) {
if (isis_sp(s, t[k]) && find(ans.begin(), ans.end(), t[k]) == ans.end())ans.push_back(t[k]);
if (isis_sp(t, s[k]) && find(ans.begin(), ans.end(), s[k]) == ans.end())ans.push_back(s[k]);
}
return ans;
}
}
// ????????¨???????????????
//???????????£????????¨???????????¨assert(false)
Point is_ss(const Line &s, const Line& t) {
if (isis_ss(s, t)) {
for (int k = 0; k < 2; ++k) {
for (int l = 0; l < 2; ++l) {
if (s[k] == t[l])return s[k];
}
}
return is_ll(s, t);
}
else {
//??????isis_ss?????????
assert(false);
return Point(0, 0);
}
}
// ????????¨???????????????
vector<Point> is_ss2(const Line &s, const Line& t) {
vector<Point> kouho(is_ll2(s, t));
vector<Point>ans;
for (auto p : kouho) {
if (isis_sp(s, p) && isis_sp(t, p))ans.emplace_back(p);
}
return ans;
}
// ??´?????¨???????????¢
ld dist_lp(const Line& l, const Point& p) {
return abs(p - proj(l, p));
}
//??´?????¨??´???????????¢
ld dist_ll(const Line& l, const Line& m) {
return isis_ll(l, m) ? 0 : dist_lp(l, m.a);
}
// ??´?????¨??????????????¢
ld dist_ls(const Line& l, const Line& s) {
return isis_ls(l, s) ? 0 : min(dist_lp(l, s.a), dist_lp(l, s.b));
}
// ????????¨???????????¢
ld dist_sp(const Line& s, const Point& p) {
Point r = proj(s, p);
return isis_sp(s, r) ? abs(r - p) : min(abs(s.a - p), abs(s.b - p));
}
// ????????¨??????????????¢
ld dist_ss(const Line& s, const Line& t) {
if (isis_ss(s, t)) return 0;
return min({ dist_sp(s, t.a), dist_sp(s, t.b), dist_sp(t, s.a), dist_sp(t, s.b) });
}
//??´?????¨??´?????????????????????????????????
Line bisection(const Line &s, const Line &t) {
const Point laglanju(is_ll(s, t));
const Point avec = !(abs(laglanju - s[0])<eps) ? s[0] - laglanju : s[1] - laglanju;
const Point bvec = !(abs(laglanju - t[0])<eps) ? t[0] - laglanju : t[1] - laglanju;
return Line(laglanju, laglanju + (abs(bvec)*avec + abs(avec)*bvec) / (abs(avec) + abs(bvec)));
}
//???????????´?????????????????????
//???????????´??????????????§???????????¨????¢?????????¨?????????
Point inner_center(const vector<Line>&ls) {
vector<Point>vertics;
for (int i = 0; i <static_cast<int>(ls.size()); ++i) {
vertics.push_back(is_ll(ls[i], ls[(i + 1) % 3]));
}
if (vertics[0] == vertics[1] || vertics[1] == vertics[2] || vertics[2] == vertics[0])return vertics[0];
Line bi1(bisection(Line(vertics[0], vertics[1]), Line(vertics[0], vertics[2])));
Line bi2(bisection(Line(vertics[1], vertics[2]), Line(vertics[1], vertics[0])));
if (bi1[0] == bi2[0])return bi1[0];
else {
return is_ll(bi1, bi2);
}
}
//???????????´?????????????????????
//???????????´??????????????§???????????¨????¢?????????¨?????????
vector<Point> ex_center(const vector<Line>&ls) {
vector<Point>vertics;
for (int i = 0; i < static_cast<int>(ls.size()); ++i) {
vertics.push_back(is_ll(ls[i], ls[(i + 1) % 3]));
}
if (abs(vertics[0] - vertics[1])<eps || abs(vertics[1] - vertics[2])<eps || (abs(vertics[2] - vertics[0])<eps))return vector<Point>();
vector<Point>ecs;
for (int i = 0; i < 3; ++i) {
Line bi1(bisection(Line(vertics[i], vertics[i] * 2.0l - vertics[(i + 2) % 3]), Line(vertics[i], vertics[(i + 1) % 3])));
Line bi2(bisection(Line(vertics[(i + 1) % 3], vertics[(i + 1) % 3] * 2.0l - vertics[(i + 2) % 3]), Line(vertics[(i + 1) % 3], vertics[i])));
ecs.push_back(is_ll(bi1, bi2));
}
return ecs;
}
//a,b:??????
//c:????????§??????
//???????????´?????????????????¢?????????????±??????????
vector<Point> same_dis(const vector<Line>&ls) {
vector<Point>vertics;
vertics.push_back(is_ll(ls[0], ls[2]));
vertics.push_back(is_ll(ls[1], ls[2]));
if (abs(vertics[0] - vertics[1]) < eps)return vector<Point>{vertics[0]};
Line bis(bisection(ls[0], ls[1]));
vector<Point>ecs;
Line abi(bisection(Line(vertics[0], vertics[1]), ls[0]));
ecs.push_back(is_ll(bis, abi));
Line bbi(bisection(Line(vertics[0], 2.l*vertics[0] - vertics[1]), ls[0]));
ecs.push_back(is_ll(bis, bbi));
return ecs;
}
/* ??? */
// ?????¨????????????
vector<Point> is_cc(const Circle& c1, const Circle& c2) {
vector<Point> res;
ld d = abs(c1.p - c2.p);
ld rc = (d * d + c1.r * c1.r - c2.r * c2.r) / (2 * d);
ld dfr = c1.r * c1.r - rc * rc;
if (abs(dfr) < eps) dfr = 0.0;
else if (dfr < 0.0) return res; // no intersection
ld rs = sqrt(dfr);
Point diff = (c2.p - c1.p) / d;
res.push_back(c1.p + diff * Point(rc, rs));
if (dfr != 0.0) res.push_back(c1.p + diff * Point(rc, -rs));
return res;
}
//???????????????????????????
/* 0 => out
1 => on
2 => in*/
int is_in_Circle(const Circle &cir, const Point& p) {
ld dis = abs(cir.p - p);
if (dis > cir.r + eps)return 0;
else if (dis < cir.r - eps)return 2;
else return 1;
}
//???lc??????rc??????????????????
/*0 => out
1 => on
2 => in*/
int Circle_in_Circle(const Circle &lc, const Circle&rc) {
ld dis = abs(lc.p - rc.p);
if (dis < rc.r - lc.r - eps)return 2;
else if (dis>rc.r - lc.r + eps)return 0;
else return 1;
}
// ?????¨??´????????????
vector<Point> is_lc(const Circle& c, const Line& l) {
vector<Point> res;
ld d = dist_lp(l, c.p);
if (d < c.r + eps) {
ld len = (d > c.r) ? 0.0 : sqrt(c.r * c.r - d * d); //safety;
Point nor = (l.a - l.b) / abs(l.a - l.b);
res.push_back(proj(l, c.p) + len * nor);
res.push_back(proj(l, c.p) - len * nor);
}
return res;
}
// ?????¨??????????????¢
vector<Point> is_sc(const Circle& c, const Line& l) {
vector<Point> v = is_lc(c, l), res;
for (Point p : v)
if (isis_sp(l, p)) res.push_back(p);
return res;
}
// ?????¨????????\???
vector<Line> tangent_cp(const Circle& c, const Point& p) {
vector<Line> ret;
Point v = c.p - p;
ld d = abs(v);
ld l = sqrt(norm(v) - c.r * c.r);
if (isnan(l)) { return ret; }
Point v1 = v * Point(l / d, c.r / d);
Point v2 = v * Point(l / d, -c.r / d);
ret.push_back(Line(p, p + v1));
if (l < eps) return ret;
ret.push_back(Line(p, p + v2));
return ret;
}
// ?????¨????????\???
vector<Line> tangent_cc(const Circle& c1, const Circle& c2) {
vector<Line> ret;
if (abs(c1.p - c2.p) - (c1.r + c2.r) > -eps) {
Point center = (c1.p * c2.r + c2.p * c1.r) / (c1.r + c2.r);
ret = tangent_cp(c1, center);
}
if (abs(c1.r - c2.r) > eps) {
Point out = (-c1.p * c2.r + c2.p * c1.r) / (c1.r - c2.r);
vector<Line> nret = tangent_cp(c1, out);
ret.insert(ret.end(), all(nret));
}
else {
Point v = c2.p - c1.p;
v /= abs(v);
Point q1 = c1.p + v * Point(0, 1) * c1.r;
Point q2 = c1.p + v * Point(0, -1) * c1.r;
ret.push_back(Line(q1, q1 + v));
ret.push_back(Line(q2, q2 + v));
}
return ret;
}
//??????????????????????????¢???
ld two_Circle_area(const Circle&l, const Circle&r) {
ld dis = abs(l.p - r.p);
if (dis > l.r + r.r)return 0;
else if (dis + r.r < l.r) {
return r.r*r.r*pi;
}
else if (dis + l.r < r.r) {
return l.r*l.r*pi;
}
else {
ld ans = (l.r)*(l.r)*acos((dis*dis + l.r*l.r - r.r*r.r) / (2 * dis*l.r)) +
(r.r)*(r.r)*acos((dis*dis + r.r*r.r - l.r*l.r) / (2 * dis*r.r)) -
sqrt(4 * dis*dis*l.r*l.r - (dis*dis + l.r*l.r - r.r*r.r)*(dis*dis + l.r*l.r - r.r*r.r)) / 2;
return ans;
}
}
/* ????§???¢ */
typedef vector<Point> Polygon;
// ??¢???
ld area(const Polygon &p) {
ld res = 0;
int n = p.size();
rep(j, n) res += cross(p[j], p[(j + 1) % n]);
return res / 2;
}
//????§???¢????????¢??????
bool is_counter_clockwise(const Polygon &poly) {
ld angle = 0;
int n = poly.size();
rep(i, n) {
Point a = poly[i], b = poly[(i + 1) % n], c = poly[(i + 2) % n];
angle += arg((c - b) / (b - a));
}
return angle > eps;
}
// ??????????????????
/*0 => out
1 => on
2 => in*/
int is_in_Polygon(const Polygon &poly, const Point& p) {
ld angle = 0;
int n = poly.size();
rep(i, n) {
Point a = poly[i], b = poly[(i + 1) % n];
if (isis_sp(Line(a, b), p)) return 1;
angle += arg((b - p) / (a - p));
}
return eq(angle, 0) ? 0 : 2;
}
//??????????????????2?????????
enum { out, on, in };
int convex_contains(const Polygon &P, const Point &p) {
const int n = P.size();
Point g = (P[0] + P[n / 3] + P[2 * n / 3]) / 3.0l; // inner-point
int a = 0, b = n;
while (a + 1 < b) { // invariant: c is in fan g-P[a]-P[b]
int c = (a + b) / 2;
if (cross(P[a] - g, P[c] - g) > 0) { // angle < 180 deg
if (cross(P[a] - g, p - g) > 0 && cross(P[c] - g, p - g) < 0) b = c;
else a = c;
}
else {
if (cross(P[a] - g, p - g) < 0 && cross(P[c] - g, p - g) > 0) a = c;
else b = c;
}
}
b %= n;
if (cross(P[a] - p, P[b] - p) < 0) return 0;
if (cross(P[a] - p, P[b] - p) > 0) return 2;
return 1;
}
// ??????
//???????????????????????¨????????????????????§??¨???
Polygon convex_hull(vector<Point> ps) {
int n = ps.size();
int k = 0;
sort(ps.begin(), ps.end());
Polygon ch(2 * n);
for (int i = 0; i < n; ch[k++] = ps[i++])
while (k >= 2 && ccw(ch[k - 2], ch[k - 1], ps[i]) <= 0) --k;
for (int i = n - 2, t = k + 1; i >= 0; ch[k++] = ps[i--])
while (k >= t && ccw(ch[k - 2], ch[k - 1], ps[i]) <= 0) --k;
ch.resize(k - 1);
return ch;
}
//????????????
vector<Polygon> convex_cut(const Polygon &ps, const Line& l) {
int n = ps.size();
Polygon q;
Polygon r;
rep(i, n) {
Point a = ps[i], b = ps[(i + 1) % n];
Line m = Line(a, b);
if (ccw(l.a, l.b, a) != -1) q.push_back(a);
if (ccw(l.a, l.b, a) != 1) r.push_back(a);
if (ccw(l.a, l.b, a) * ccw(l.a, l.b, b) < 0 && isis_ll(l, m)) {
q.push_back(is_ll(l, m));
r.push_back(is_ll(l, m));
}
}
const vector<Polygon>polys{ q,r };
return polys;
}
/* ??¢??¬??????????????? */
void add_Point(vector<Point> &ps, const Point p) {
for (Point q : ps) if (abs(q - p) < eps) return;
ps.push_back(p);
}
typedef ld Weight;
struct edge {
int id;
int src, dst;
Weight kaku;
edge(int id_,int src, int dst, Weight weight) :
id(id_),src(src), dst(dst), kaku(weight) { }
};
typedef vector<edge> edges;
typedef vector<edges> graph;
void add_edge(graph &g, const int id,const int from, const int to, const Weight& weight) {
g[from].push_back(edge{ id,from, to, weight });
}
graph segment_arrangement(const vector<Line> &s, const vector<Point> &p) {
int n = p.size(), m = s.size();
graph g(n);
int aid = 0;
rep(i, m) {
vector<pair<ld, int>> vec;
rep(j, n) if (isis_sp(s[i], p[j]))
vec.emplace_back(abs(s[i].a - p[j]), j);
sort(all(vec));
rep(j, vec.size() - 1) {
int from = vec[j].second, to = vec[j + 1].second;
{
ld theta = dot(p[to] - p[from], Point(1, 0)) / abs(p[to] - p[from]);
ld kaku =(p[to]-p[from]).imag() > 0 ? acos(theta) : -acos(theta);
add_edge(g, aid++, from, to, kaku);
}
{
ld theta = dot(p[from] - p[to], Point(1, 0)) / abs(p[to] - p[from]);
ld kaku = (p[from] - p[to]).imag() > 0 ? acos(theta) : -acos(theta);
add_edge(g, aid++, to, from, kaku);
}
}
}
return g;
}
Point start, goal;
vector<int>ss, gs;
vector<Point>crss;
graph sennbunn_arrangement(const vector<Line>&s) {
for (int i = 0; i < static_cast<int>(s.size()); ++i) {
for (int j = i + 1; j < static_cast<int>(s.size()); ++j) {
if (isis_ss(s[i], s[j])) {
crss.push_back(is_ll2(s[i], s[j])[0]);
}
}
}
for (int i = 0; i <static_cast<int>(s.size()); ++i) {
crss.push_back(s[i][0]);
crss.push_back(s[i][1]);
}
sort(crss.begin(), crss.end());
crss.erase(unique(crss.begin(), crss.end()), crss.end());
for (int i = 0; i < crss.size(); ++i) {
if (crss[i] == start) {
ss.push_back(i);
}
else if (crss[i] == goal) {
gs.push_back(i);
}
}
return segment_arrangement(s, crss);
}
struct aa {
edge e;
bool isstart;
ld time;
};
class Compare {
public:
//aa?????????????????¶
bool operator()(const aa&l, const aa&r) {
return l.time> r.time;
}
};
int main() {
while (1) {
ss.clear();
gs.clear();
crss.clear();
int N; cin >> N;
if (!N)break;
vector<Line>ls;
for (int i = 0; i < N; ++i) {
int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;
Line l(Point(x1, y1), Point(x2, y2));
ls.emplace_back(l);
}
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
start = Point(sx, sy);
goal = Point(gx, gy);
graph g(sennbunn_arrangement(ls));
/*vector<edge>id_edges(10000);
for (auto es : g) {
for (auto e : es) {
id_edges[e.id] = e;
}
}*/
priority_queue<aa, vector<aa>, Compare>que;
int num = 9000;
for (auto s : ss) {
que.push(aa{ edge(num++ , -1, s, -1), true, 0 });
}
ld ans = -1;
vector<ld>memo(10000, 1e18);
while (!que.empty()) {
auto atop(que.top());
que.pop();
const int aid = atop.e.id;
const int asrc = atop.e.dst;
const ld atime = atop.time;
const ld akaku = atop.e.kaku;
if (find(gs.begin(), gs.end(), asrc) != gs.end()) {
ans = atime;
break;
}
for (auto e : g[asrc]) {
ld needkaku = min(abs(akaku - e.kaku), 2 * pi - abs(akaku - e.kaku));
ld sum = atime+ needkaku;
if (atop.isstart)sum = 0;
if (memo[e.id] > sum) {
memo[e.id] = sum;
que.push(aa{ e,false,sum });
}
}
}
if (ans < 0)cout << -1 << endl;
else cout << setprecision(12)<<fixed<<ans/pi*180 << endl;
}
return 0;
}
``` |
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
/*
if(s == g) {
cout << 0 << endl;
continue;
}
*/
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
} | ### Prompt
Please create a solution in CPP to the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
typedef complex<double> P;
const double EPS = 1e-8;
// 誤差を加味した符号判定
int sign(double x){ return x > EPS ? 1 : x < -EPS ? -1 : 0; }
// 内積・外積
double dot(P a, P b){return real(conj(a) * b);}
double cross(P a, P b){return imag(conj(a) * b);}
// OAとOBのなす符号付き角度 [-pi, pi]
// example : (1, 0), (0, 1) -> pi/2
double angle(P a, P b){return arg(conj(a) * b);}
// aをc中心にb[rad]回転
P rotate(P a, double b, P c = P()){return (a - c) * polar(1.0, b) + c;}
int ccw(P a, P b, P c) {
b -= a; c -= a;
if (cross(b, c) > +EPS) return +1; // 反時計回り
if (cross(b, c) < -EPS) return -1; // 時計回り
if (dot(b, c) < -EPS) return +2; // c--a--b の順番で一直線上
if (norm(b) + EPS < norm(c)) return -2; // a--b--c の順番で一直線上
return 0; // 点が線分ab上にある
}
enum{ OUT, ON, IN };
// Pointの比較をしたいときだけ定義する.
namespace std{
bool operator < (const P& a, const P& b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
};
typedef vector<P> L;
P vec(L l){return l[1] - l[0];}
// 線分と点の交差判定(端点の処理に注意)(端点は含むけれども誤差に注意)
// verify : AOJ1279, AOJ2506
bool iSP(L s, P p) {return ccw(s[0], s[1], p) == 0;}
// 直線と直線の交点
// Verified: AOJ2579
// size()によって場合分け
// *4 : 直線が重なる *1 : 交点が1つ存在 *0 : 直線が交差しない
vector<P> pLL(L l, L m){
double A = cross(vec(l), vec(m));
double B = cross(vec(l), l[1] - m[0]);
if(sign(A) == 0 && sign(B) == 0) return {l[0], l[1], m[0], m[1]}; // 二直線が重なっている
if(sign(A) == 0) return{}; // 直線が交わらない
return {m[0] + vec(m) * B / A};
}
vector<P> pSS(L l, L m){
vector<P> res;
auto find = [&](P p){
for(P r : res) if(sign(abs(r - p)) == 0)
return true;
return false;
};
for(P p : pLL(l, m))
if(iSP(l,p) && iSP(m,p) && !find(p)) // 片方が直線の場合は適宜変えること
res.push_back(p);
return res;
}
// 入力
// ss : 線分のリスト
//
// 出力
// ps : グラフの頂点番号に対応する点が入る
// 返り値 : 上の説明のグラフ
//
// Verified
// AOJ 2113
typedef vector<int> Node;
typedef vector<Node> Graph;
Graph segment_arrangement(const vector<L> &ss, vector<P> &ps) {
for (int i = 0; i < ss.size(); i++) {
ps.push_back( ss[i][0] );
ps.push_back( ss[i][1] );
for (int j = i+1; j < ss.size(); j++){
auto cp = pSS(ss[i], ss[j]);
if (!cp.empty()) {
assert(cp.size() == 1);
ps.push_back( cp.back() );
}
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph g(ps.size());
for (int i = 0; i < ss.size(); i++) {
vector<int> on;
for (int j = 0; j < ps.size(); j++){
if (iSP(ss[i], ps[j])){
on.push_back(j);
}
}
for (int j = 0; j + 1 < on.size(); j++) {
for(int k = j + 1; k < on.size(); k++) {
int a = on[j], b = on[k];
g[a].push_back( b );
g[b].push_back( a );
}
}
}
return g;
}
// 線分併合
//
// 線分のリストからオーバーラップするものたちをまとめ,新しい線分のリストを作る.
// 元々の線分のリストにおける順番は破壊される.
//
// not verified
void merge_segments(vector<L>& segs) {
auto merge_if_able = [](L& s, L t){
if (abs(cross(s[1]-s[0], t[1]-t[0])) > EPS) return false;
//if (sign(cross(vec(s), vec(t))) != 0) return false;
if (ccw(s[0], t[0], s[1]) == +1 ||
ccw(s[0], t[0], s[1]) == -1) return false; // not on the same line
if (ccw(s[0], s[1], t[0]) == -2 ||
ccw(t[0], t[1], s[0]) == -2) return false; // separated
s = { min(s[0], t[0]), max(s[1], t[1]) };
return true;
};
for (int i = 0; i < segs.size(); ++i)
if (segs[i][1] < segs[i][0])
swap(segs[i][1], segs[i][0]);
for (int i = 0; i < segs.size(); ++i)
for (int j = i+1; j < segs.size(); ++j)
if (merge_if_able(segs[i], segs[j]))
segs[j--] = segs.back(), segs.pop_back();
}
P input() {
double x, y;
cin >> x >> y;
return {x, y};
}
typedef tuple<double, int, int> T;
const int MAX = 500;
const double INF = 1e64;
int main(){
int n;
while(cin >> n && n > 0){
vector<L> lines(n);
REP(i, n) {
P a = input();
P b = input();
lines[i] = {a, b};
}
merge_segments(lines);
//assert(size == lines.size());
vector<P> ps;
Graph G = segment_arrangement(lines, ps);
/*
REP(i, G.size()){
cout << i << ":";
for(int v : G[i]) cout << v << " ";
cout << endl;
}
*/
assert(ps.size() < MAX);
REP(i, ps.size()) REP(j, i) {
assert(abs(ps[i] - ps[j]) > EPS);
}
auto find = [](const vector<P>& pv, P p) -> int {
for(int i = 0; i < pv.size(); i++) {
auto q = pv[i];
if(abs(p - q) < EPS) {
return i;
}
}
return -1;
};
P sp = input();
P gp = input();
int s = find(ps, sp);
int g = find(ps, gp);
/*
if(s == g) {
cout << 0 << endl;
continue;
}
*/
assert(s != -1 && g != -1);
priority_queue<T, vector<T>, greater<T>> que;
double dist[MAX][MAX] = {};
REP(i, MAX) REP(j, MAX) dist[i][j] = INF;
for(int u : G[s]) {
dist[s][u] = 0.0;
que.push(T(0.0, s, u));
}
double ans = INF;
while(!que.empty()) {
T t = que.top(); que.pop();
double d;
int u, v;
tie(d, u, v) = t;
if(v == g) {
ans = d;
break;
}
for(int w : G[v]) {
P p = ps[v] - ps[u];
P q = ps[w] - ps[v];
double th = abs(angle(p, q)) / M_PI * 180.0;
double nd = d + th;
if(dist[v][w] > nd) {
dist[v][w] = nd;
que.push(T(nd, v, w));
}
}
}
if(ans == INF) {
cout << -1 << endl;
} else {
printf("%.12f\n", ans);
}
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define FR first
#define SC second
#define all(v) (v).begin(), (v).end()
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define reps(i, f, n) for(int i = (int)(f); i < (int)(n); i++)
#define each(a, b) for(auto& a : b)
typedef pair<int, int> P;
const int inf = 1LL << 55;
#define EPS (1e-10)
#define equals(a, b) (fabs((a)-(b)) < EPS)
#define lt(a, b) ((a) - (b) < -EPS)
// ???/????????????
struct Point {
double x, y;
Point(double x = 0.0, double y = 0.0):x(x), y(y){}
Point operator + (Point p) { return Point(x + p.x, y + p.y); }
Point operator - (Point p) { return Point(x - p.x, y - p.y); }
Point operator * (double a) { return Point(x * a, y * a); }
Point operator / (double a) { return Point(x / a, y / a); }
double abs() { return sqrt(norm()); }
double norm() { return x*x + y*y; }
bool operator < (const Point& p) const {
return x != p.x ? x < p.x : y < p.y;
}
bool operator == (const Point& p) const {
return fabs(x - p.x) < EPS && fabs(y - p.y) < EPS;
}
};
typedef Point Vector;
// ???
struct Circle {
Point c;
double r;
Circle(Point c = Point(), double r = 0.0):c(c), r(r){}
};
// ????§???¢
typedef vector<Point> Polygon;
// ??????/??´???
struct Segment {
Point p1, p2;
Segment(Point p1 = Point(), Point p2 = Point()):p1(p1), p2(p2){}
};
typedef Segment Line;
// ????????????????????????
double norm(Vector v)
{
return v.x*v.x + v.y*v.y;
}
// ?????????????????§??????
double abs(Vector v)
{
return sqrt(norm(v));
}
// ?????????????????????
double dot(Vector a, Vector b)
{
return a.x*b.x + a.y*b.y;
}
// ??????????????????????????§??????
double cross(Vector a, Vector b)
{
return a.x*b.y - a.y*b.x;
}
// ??´?????????
bool isOrthogonal(Vector a, Vector b)
{
return equals(dot(a, b), 0.0);
}
bool isOrthogonal(Point a1, Point a2, Point b1, Point b2)
{
return isOrthogonal(a1 - a2, b1 - b2);
}
bool isOrthogonal(Segment s1, Segment s2)
{
return equals(dot(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
// ????????????
bool isParallel(Vector a, Vector b)
{
return equals(cross(a, b), 0.0);
}
bool isParallel(Point a1, Point a2, Point b1, Point b2)
{
return isParallel(a1 - a2, b1 - b2);
}
bool isParallel(Segment s1, Segment s2)
{
return equals(cross(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
// ?°???±
Point project(Segment s, Point p)
{
Vector base = s.p2 - s.p1;
double r = dot(p - s.p1, base) / norm(base);
return s.p1 + base * r;
}
// ????°?
Point reflect(Segment s, Point p)
{
return p + (project(s, p) - p) * 2.0;
}
static const int COUNTER_CLOCKWISE = 1;
static const int CLOCKWISE = -1;
static const int ONLINE_BACK = 2;
static const int ONLINE_FRONT = -2;
static const int ON_SEGMENT = 0;
// ???????¨???????
int ccw(Point p0, Point p1, Point p2)
{
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a, b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a, b) < -EPS) return CLOCKWISE;
if(dot(a, b) < -EPS) return ONLINE_BACK;
if(a.norm() < b.norm()) return ONLINE_FRONT;
return ON_SEGMENT;
}
// ????????????
bool intersect(Point p1, Point p2, Point p3, Point p4)
{
return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 &&
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0);
}
bool intersect(Segment s1, Segment s2)
{
return intersect(s1.p1, s1.p2, s2.p1, s2.p2);
}
bool intersect(Segment s, Point p)
{
return (ccw(s.p1, s.p2, p) == ON_SEGMENT);
}
// ?????????????????¢
double getDistance(Point a, Point b)
{
return abs(a - b);
}
// ??´?????¨?????¨????????¢
double getDistanceLP(Line l, Point p)
{
return abs(cross(l.p2 - l.p1, p - l.p1) / abs(l.p2 - l.p1));
}
// ????????¨?????¨????????¢
double getDistanceSP(Segment s, Point p)
{
if(dot(s.p2 - s.p1, p - s.p1) < 0.0) return abs(p - s.p1);
if(dot(s.p1 - s.p2, p - s.p2) < 0.0) return abs(p - s.p2);
return getDistanceLP(s, p);
}
// ????????????????????¢
double getDistance(Segment s1, Segment s2)
{
if(intersect(s1, s2)) return 0.0;
return min(min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)),
min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2)));
}
// ???????????????
Point getCrossPoint(Segment s1, Segment s2)
{
Vector base = s2.p2 - s2.p1;
double d1 = abs(cross(base, s1.p1 - s2.p1));
double d2 = abs(cross(base, s1.p2 - s2.p1));
double t = d1 / (d1 + d2);
return s1.p1 + (s1.p2 - s1.p1) * t;
}
// ????????????
bool merge_if_able(Segment &s1, Segment s2)
{
if(abs(cross(s1.p2 - s1.p1, s2.p2 - s2.p1)) > EPS) return false;
if(ccw(s1.p1, s2.p1, s1.p2) == COUNTER_CLOCKWISE ||
ccw(s1.p1, s2.p1, s1.p2) == CLOCKWISE) return false;
if(ccw(s1.p1, s1.p2, s2.p1) == ONLINE_FRONT ||
ccw(s2.p1, s2.p2, s1.p1) == ONLINE_FRONT) return false;
s1 = Segment(min(s1.p1, s2.p1), max(s1.p2, s2.p2));
return true;
}
void merge_segments(vector<Segment>& segs)
{
for(int i = 0; i < segs.size(); i++) {
if(segs[i].p2 < segs[i].p1) swap(segs[i].p1, segs[i].p2);
}
for(int i = 0; i < segs.size(); i++) {
for(int j = i+1; j < segs.size(); j++) {
if(merge_if_able(segs[i], segs[j])) {
segs[j--] = segs.back(), segs.pop_back();
}
}
}
}
// ????????¢??¬???????????????
typedef vector< vector<int> > Graph;
Graph segment_arrangement(vector<Segment>& segs, vector<Point>& ps)
{
for(int i = 0; i < segs.size(); i++) {
ps.push_back(segs[i].p1);
ps.push_back(segs[i].p2);
for(int j = i+1; j < segs.size(); j++) {
if(intersect(segs[i], segs[j])) ps.push_back(getCrossPoint(segs[i], segs[j]));
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph graph(ps.size());
for(int i = 0; i < segs.size(); i++) {
vector<int> ls;
for(int j = 0; j < ps.size(); j++) {
if(intersect(segs[i], ps[j])) {
ls.push_back(j);
}
}
sort(ls.begin(), ls.end());
for(int j = 0; j+1 < ls.size(); j++) {
int u = ls[j], v = ls[j+1];
graph[u].push_back(v);
graph[v].push_back(u);
}
}
return graph;
}
// ???ABC????±???????
double getAngle(Point a, Point b, Point c)
{
Vector v = b - a, w = c - b;
double alpha = atan2(v.y, v.x), beta = atan2(w.y, w.x);
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180 / M_PI;
return min(theta, 360 - theta);
}
Graph graph;
double dijkstra(int si, int gi, vector<Point> ps)
{
vector< vector<double> > mincost(graph.size(), vector<double>(graph.size(),inf));
// ?????????????????¨??°????????????
typedef tuple<double, int, int> T;
priority_queue<T, vector<T>, greater<T> > que;
for(int to : graph[si]) {
mincost[to][si] = 0.0;
que.push(make_tuple(0.0, to, si));
}
while(!que.empty()) {
double c; int now, prev;
tie(c, now, prev) = que.top(); que.pop();
if(now == gi) return c;
for(int to : graph[now]) {
double cost = c + getAngle(ps[prev], ps[now], ps[to]);
if(cost - mincost[to][now] < -EPS) {
mincost[to][now] = cost;
que.push(make_tuple(cost, to, now));
}
}
}
return -1;
}
signed main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
cout << fixed << setprecision(12);
int n;
while(cin >> n, n) {
vector<Segment> ss(n);
Point s, g;
rep(i, n) cin >> ss[i].p1.x >> ss[i].p1.y >> ss[i].p2.x >> ss[i].p2.y;
cin >> s.x >> s.y >> g.x >> g.y;
vector<Point> ps;
merge_segments(ss);
graph = segment_arrangement(ss, ps);
int si = -1, gi = -1;
rep(i, ps.size()) {
if(ps[i] == s) si = i;
if(ps[i] == g) gi = i;
}
double ans = dijkstra(si, gi, ps);
if(ans == -1) cout << -1 << endl;
else cout << ans << endl;
}
return 0;
} | ### Prompt
Construct a Cpp code solution to the problem outlined:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define FR first
#define SC second
#define all(v) (v).begin(), (v).end()
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define reps(i, f, n) for(int i = (int)(f); i < (int)(n); i++)
#define each(a, b) for(auto& a : b)
typedef pair<int, int> P;
const int inf = 1LL << 55;
#define EPS (1e-10)
#define equals(a, b) (fabs((a)-(b)) < EPS)
#define lt(a, b) ((a) - (b) < -EPS)
// ???/????????????
struct Point {
double x, y;
Point(double x = 0.0, double y = 0.0):x(x), y(y){}
Point operator + (Point p) { return Point(x + p.x, y + p.y); }
Point operator - (Point p) { return Point(x - p.x, y - p.y); }
Point operator * (double a) { return Point(x * a, y * a); }
Point operator / (double a) { return Point(x / a, y / a); }
double abs() { return sqrt(norm()); }
double norm() { return x*x + y*y; }
bool operator < (const Point& p) const {
return x != p.x ? x < p.x : y < p.y;
}
bool operator == (const Point& p) const {
return fabs(x - p.x) < EPS && fabs(y - p.y) < EPS;
}
};
typedef Point Vector;
// ???
struct Circle {
Point c;
double r;
Circle(Point c = Point(), double r = 0.0):c(c), r(r){}
};
// ????§???¢
typedef vector<Point> Polygon;
// ??????/??´???
struct Segment {
Point p1, p2;
Segment(Point p1 = Point(), Point p2 = Point()):p1(p1), p2(p2){}
};
typedef Segment Line;
// ????????????????????????
double norm(Vector v)
{
return v.x*v.x + v.y*v.y;
}
// ?????????????????§??????
double abs(Vector v)
{
return sqrt(norm(v));
}
// ?????????????????????
double dot(Vector a, Vector b)
{
return a.x*b.x + a.y*b.y;
}
// ??????????????????????????§??????
double cross(Vector a, Vector b)
{
return a.x*b.y - a.y*b.x;
}
// ??´?????????
bool isOrthogonal(Vector a, Vector b)
{
return equals(dot(a, b), 0.0);
}
bool isOrthogonal(Point a1, Point a2, Point b1, Point b2)
{
return isOrthogonal(a1 - a2, b1 - b2);
}
bool isOrthogonal(Segment s1, Segment s2)
{
return equals(dot(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
// ????????????
bool isParallel(Vector a, Vector b)
{
return equals(cross(a, b), 0.0);
}
bool isParallel(Point a1, Point a2, Point b1, Point b2)
{
return isParallel(a1 - a2, b1 - b2);
}
bool isParallel(Segment s1, Segment s2)
{
return equals(cross(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
// ?°???±
Point project(Segment s, Point p)
{
Vector base = s.p2 - s.p1;
double r = dot(p - s.p1, base) / norm(base);
return s.p1 + base * r;
}
// ????°?
Point reflect(Segment s, Point p)
{
return p + (project(s, p) - p) * 2.0;
}
static const int COUNTER_CLOCKWISE = 1;
static const int CLOCKWISE = -1;
static const int ONLINE_BACK = 2;
static const int ONLINE_FRONT = -2;
static const int ON_SEGMENT = 0;
// ???????¨???????
int ccw(Point p0, Point p1, Point p2)
{
Vector a = p1 - p0;
Vector b = p2 - p0;
if(cross(a, b) > EPS) return COUNTER_CLOCKWISE;
if(cross(a, b) < -EPS) return CLOCKWISE;
if(dot(a, b) < -EPS) return ONLINE_BACK;
if(a.norm() < b.norm()) return ONLINE_FRONT;
return ON_SEGMENT;
}
// ????????????
bool intersect(Point p1, Point p2, Point p3, Point p4)
{
return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 &&
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0);
}
bool intersect(Segment s1, Segment s2)
{
return intersect(s1.p1, s1.p2, s2.p1, s2.p2);
}
bool intersect(Segment s, Point p)
{
return (ccw(s.p1, s.p2, p) == ON_SEGMENT);
}
// ?????????????????¢
double getDistance(Point a, Point b)
{
return abs(a - b);
}
// ??´?????¨?????¨????????¢
double getDistanceLP(Line l, Point p)
{
return abs(cross(l.p2 - l.p1, p - l.p1) / abs(l.p2 - l.p1));
}
// ????????¨?????¨????????¢
double getDistanceSP(Segment s, Point p)
{
if(dot(s.p2 - s.p1, p - s.p1) < 0.0) return abs(p - s.p1);
if(dot(s.p1 - s.p2, p - s.p2) < 0.0) return abs(p - s.p2);
return getDistanceLP(s, p);
}
// ????????????????????¢
double getDistance(Segment s1, Segment s2)
{
if(intersect(s1, s2)) return 0.0;
return min(min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)),
min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2)));
}
// ???????????????
Point getCrossPoint(Segment s1, Segment s2)
{
Vector base = s2.p2 - s2.p1;
double d1 = abs(cross(base, s1.p1 - s2.p1));
double d2 = abs(cross(base, s1.p2 - s2.p1));
double t = d1 / (d1 + d2);
return s1.p1 + (s1.p2 - s1.p1) * t;
}
// ????????????
bool merge_if_able(Segment &s1, Segment s2)
{
if(abs(cross(s1.p2 - s1.p1, s2.p2 - s2.p1)) > EPS) return false;
if(ccw(s1.p1, s2.p1, s1.p2) == COUNTER_CLOCKWISE ||
ccw(s1.p1, s2.p1, s1.p2) == CLOCKWISE) return false;
if(ccw(s1.p1, s1.p2, s2.p1) == ONLINE_FRONT ||
ccw(s2.p1, s2.p2, s1.p1) == ONLINE_FRONT) return false;
s1 = Segment(min(s1.p1, s2.p1), max(s1.p2, s2.p2));
return true;
}
void merge_segments(vector<Segment>& segs)
{
for(int i = 0; i < segs.size(); i++) {
if(segs[i].p2 < segs[i].p1) swap(segs[i].p1, segs[i].p2);
}
for(int i = 0; i < segs.size(); i++) {
for(int j = i+1; j < segs.size(); j++) {
if(merge_if_able(segs[i], segs[j])) {
segs[j--] = segs.back(), segs.pop_back();
}
}
}
}
// ????????¢??¬???????????????
typedef vector< vector<int> > Graph;
Graph segment_arrangement(vector<Segment>& segs, vector<Point>& ps)
{
for(int i = 0; i < segs.size(); i++) {
ps.push_back(segs[i].p1);
ps.push_back(segs[i].p2);
for(int j = i+1; j < segs.size(); j++) {
if(intersect(segs[i], segs[j])) ps.push_back(getCrossPoint(segs[i], segs[j]));
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
Graph graph(ps.size());
for(int i = 0; i < segs.size(); i++) {
vector<int> ls;
for(int j = 0; j < ps.size(); j++) {
if(intersect(segs[i], ps[j])) {
ls.push_back(j);
}
}
sort(ls.begin(), ls.end());
for(int j = 0; j+1 < ls.size(); j++) {
int u = ls[j], v = ls[j+1];
graph[u].push_back(v);
graph[v].push_back(u);
}
}
return graph;
}
// ???ABC????±???????
double getAngle(Point a, Point b, Point c)
{
Vector v = b - a, w = c - b;
double alpha = atan2(v.y, v.x), beta = atan2(w.y, w.x);
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180 / M_PI;
return min(theta, 360 - theta);
}
Graph graph;
double dijkstra(int si, int gi, vector<Point> ps)
{
vector< vector<double> > mincost(graph.size(), vector<double>(graph.size(),inf));
// ?????????????????¨??°????????????
typedef tuple<double, int, int> T;
priority_queue<T, vector<T>, greater<T> > que;
for(int to : graph[si]) {
mincost[to][si] = 0.0;
que.push(make_tuple(0.0, to, si));
}
while(!que.empty()) {
double c; int now, prev;
tie(c, now, prev) = que.top(); que.pop();
if(now == gi) return c;
for(int to : graph[now]) {
double cost = c + getAngle(ps[prev], ps[now], ps[to]);
if(cost - mincost[to][now] < -EPS) {
mincost[to][now] = cost;
que.push(make_tuple(cost, to, now));
}
}
}
return -1;
}
signed main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
cout << fixed << setprecision(12);
int n;
while(cin >> n, n) {
vector<Segment> ss(n);
Point s, g;
rep(i, n) cin >> ss[i].p1.x >> ss[i].p1.y >> ss[i].p2.x >> ss[i].p2.y;
cin >> s.x >> s.y >> g.x >> g.y;
vector<Point> ps;
merge_segments(ss);
graph = segment_arrangement(ss, ps);
int si = -1, gi = -1;
rep(i, ps.size()) {
if(ps[i] == s) si = i;
if(ps[i] == g) gi = i;
}
double ans = dijkstra(si, gi, ps);
if(ans == -1) cout << -1 << endl;
else cout << ans << endl;
}
return 0;
}
``` |
#include<bits/stdc++.h>
#define f first
#define s second
#define mp make_pair
#define pi M_PI
#define inf 1e14
#define eps (1e-8)
#define MAX 1000
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y+p.y);}
Point operator-(Point p){ return Point(x-p.x,y-p.y);}
Point operator*(double k){ return Point(x*k,y*k);}
Point operator/(double k){ return Point(x/k,y/k);}
bool operator<(Point p)const{ return (x!=p.x ? x<p.x : y<p.y);}
bool operator==(Point p)const{ return fabs(x-p.x)<eps && fabs(y-p.y)<eps;}
double abs(){ return sqrt(norm());}
double norm(){ return (x*x+y*y);}
};
typedef Point Vector;
typedef vector<Point> Polygon;
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(),Point p2=Point()):p1(p1),p2(p2){}
};
typedef Segment Line;
double norm(Vector a){ return (a.x*a.x+a.y*a.y);}
double abs(Vector a){ return sqrt(norm(a));}
double dot(Vector a,Vector b){ return (a.x*b.x+a.y*b.y);}
double cross(Vector a,Vector b){ return (a.x*b.y-a.y*b.x);}
bool isParallel(Segment s,Segment t){
return equals(cross(s.p1-s.p2,t.p1-t.p2),0.0);
}
int ccw(Point p0,Point p1,Point p2){
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>eps)return 1;
if(cross(a,b)<-eps)return -1;
if(dot(a,b)<-eps)return 2;
if(a.norm()<b.norm())return -2;
return 0;
}
bool intersect(Point p1,Point p2,Point p3,Point p4){
return (ccw(p1,p2,p3)*ccw(p1,p2,p4)<=0 &&
ccw(p3,p4,p1)*ccw(p3,p4,p2)<=0);
}
bool intersect(Segment s1,Segment s2){
return intersect(s1.p1,s1.p2,s2.p1,s2.p2);
}
Point getCrossPointLL(Line a,Line b){
double A=cross(a.p2-a.p1,b.p2-b.p1);
double B=cross(a.p2-a.p1,a.p2-b.p1);
if(abs(A)<eps || abs(B)<eps)return b.p1;
return b.p1+(b.p2-b.p1)*(B/A);
}
bool merge_if_able(Segment &s,Segment t) {
if(!isParallel(s,t))return false;
if(ccw(s.p1,t.p1,s.p2)==1 ||
ccw(s.p1,t.p1,s.p2)==-1)return false;
if(ccw(s.p1,s.p2,t.p1)==-2 ||
ccw(t.p1,t.p2,s.p1)==-2)return false;
s=Segment(min(s.p1,t.p1),max(s.p2,t.p2));
return true;
}
void merge(vector<Segment>& v) {
for(int i=0;i<v.size();i++){
if(v[i].p2<v[i].p1)swap(v[i].p2,v[i].p1);
}
for(int i=0;i<v.size();i++)
for(int j=i+1;j<v.size();j++)
if(merge_if_able(v[i],v[j]))
v[j--]=v.back(),v.pop_back();
}
typedef vector<vector<int> > Graph;
Graph SegmentArrangement(vector<Segment> v,vector<Point> &ps){
for(int i=0;i<v.size();i++){
ps.push_back(v[i].p1);
ps.push_back(v[i].p2);
for(int j=i+1;j<v.size();j++){
if(intersect(v[i],v[j]))ps.push_back(getCrossPointLL(v[i],v[j]));
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
Graph g(ps.size());
for(int i=0;i<v.size();i++){
vector<pair<double,int> > list;
for(int j=0;j<ps.size();j++)
if(ccw(v[i].p1,v[i].p2,ps[j])==0)
list.push_back(mp(norm(v[i].p1-ps[j]),j));
sort(list.begin(),list.end());
for(int j=0;j<list.size()-1;j++){
int a=list[j].s,b=list[j+1].s;
g[a].push_back(b);
g[b].push_back(a);
}
}
return g;
}
class State{
public:
int n,b;
double cost;
State(int n,int b,double cost):n(n),b(b),cost(cost){}
bool operator<(State s)const{
return s.cost-cost<-eps;
}
};
Graph e;
vector<Point> vp;
Point a,b;
double getAngle(Vector v1,Vector v2){
double r=dot(v1,v2)/(abs(v1)*abs(v2));
if(r<-1.0)r=-1.0;
if(1.0<r)r=1.0;
return (acos(r)*180.0/pi);
}
double dijkstra(){
int s=0,g=0;
double d[MAX][MAX];
priority_queue<State> pq;
for(int i=0;i<vp.size();i++){
if(vp[i]==a)s=i;
if(vp[i]==b)g=i;
}
for(int i=0;i<MAX;i++)for(int j=0;j<MAX;j++)d[i][j]=inf;
for(int i=0;i<e[s].size();i++){
d[e[s][i]][s]=0;
pq.push(State(e[s][i],s,0));
}
while(pq.size()){
State u=pq.top();
pq.pop();
if(u.n==g)return u.cost;
if(d[u.n][u.b]-u.cost<-eps)continue;
for(int i=0;i<e[u.n].size();i++){
int next=e[u.n][i];
if(next==u.b)continue;
double cost=getAngle(vp[u.n]-vp[u.b],vp[next]-vp[u.n]);
if(u.cost+cost-d[next][u.n]<-eps){
d[next][u.n]=u.cost+cost;
pq.push(State(next,u.n,d[next][u.n]));
}
}
}
return -1;
}
int main()
{
int n;
while(1){
cin>>n;
if(n==0)break;
vector<Segment> vs;
for(int i=0;i<n;i++){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
vs.push_back(Segment(Point(x1,y1),Point(x2,y2)));
}
cin>>a.x>>a.y>>b.x>>b.y;
vp.clear();
vp.push_back(a);
vp.push_back(b);
merge(vs);
e=SegmentArrangement(vs,vp);
double ans=dijkstra();
if(ans==-1)cout<<-1<<endl;
else printf("%.10f\n",dijkstra());
}
}
| ### Prompt
Develop a solution in cpp to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include<bits/stdc++.h>
#define f first
#define s second
#define mp make_pair
#define pi M_PI
#define inf 1e14
#define eps (1e-8)
#define MAX 1000
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y+p.y);}
Point operator-(Point p){ return Point(x-p.x,y-p.y);}
Point operator*(double k){ return Point(x*k,y*k);}
Point operator/(double k){ return Point(x/k,y/k);}
bool operator<(Point p)const{ return (x!=p.x ? x<p.x : y<p.y);}
bool operator==(Point p)const{ return fabs(x-p.x)<eps && fabs(y-p.y)<eps;}
double abs(){ return sqrt(norm());}
double norm(){ return (x*x+y*y);}
};
typedef Point Vector;
typedef vector<Point> Polygon;
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(),Point p2=Point()):p1(p1),p2(p2){}
};
typedef Segment Line;
double norm(Vector a){ return (a.x*a.x+a.y*a.y);}
double abs(Vector a){ return sqrt(norm(a));}
double dot(Vector a,Vector b){ return (a.x*b.x+a.y*b.y);}
double cross(Vector a,Vector b){ return (a.x*b.y-a.y*b.x);}
bool isParallel(Segment s,Segment t){
return equals(cross(s.p1-s.p2,t.p1-t.p2),0.0);
}
int ccw(Point p0,Point p1,Point p2){
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>eps)return 1;
if(cross(a,b)<-eps)return -1;
if(dot(a,b)<-eps)return 2;
if(a.norm()<b.norm())return -2;
return 0;
}
bool intersect(Point p1,Point p2,Point p3,Point p4){
return (ccw(p1,p2,p3)*ccw(p1,p2,p4)<=0 &&
ccw(p3,p4,p1)*ccw(p3,p4,p2)<=0);
}
bool intersect(Segment s1,Segment s2){
return intersect(s1.p1,s1.p2,s2.p1,s2.p2);
}
Point getCrossPointLL(Line a,Line b){
double A=cross(a.p2-a.p1,b.p2-b.p1);
double B=cross(a.p2-a.p1,a.p2-b.p1);
if(abs(A)<eps || abs(B)<eps)return b.p1;
return b.p1+(b.p2-b.p1)*(B/A);
}
bool merge_if_able(Segment &s,Segment t) {
if(!isParallel(s,t))return false;
if(ccw(s.p1,t.p1,s.p2)==1 ||
ccw(s.p1,t.p1,s.p2)==-1)return false;
if(ccw(s.p1,s.p2,t.p1)==-2 ||
ccw(t.p1,t.p2,s.p1)==-2)return false;
s=Segment(min(s.p1,t.p1),max(s.p2,t.p2));
return true;
}
void merge(vector<Segment>& v) {
for(int i=0;i<v.size();i++){
if(v[i].p2<v[i].p1)swap(v[i].p2,v[i].p1);
}
for(int i=0;i<v.size();i++)
for(int j=i+1;j<v.size();j++)
if(merge_if_able(v[i],v[j]))
v[j--]=v.back(),v.pop_back();
}
typedef vector<vector<int> > Graph;
Graph SegmentArrangement(vector<Segment> v,vector<Point> &ps){
for(int i=0;i<v.size();i++){
ps.push_back(v[i].p1);
ps.push_back(v[i].p2);
for(int j=i+1;j<v.size();j++){
if(intersect(v[i],v[j]))ps.push_back(getCrossPointLL(v[i],v[j]));
}
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
Graph g(ps.size());
for(int i=0;i<v.size();i++){
vector<pair<double,int> > list;
for(int j=0;j<ps.size();j++)
if(ccw(v[i].p1,v[i].p2,ps[j])==0)
list.push_back(mp(norm(v[i].p1-ps[j]),j));
sort(list.begin(),list.end());
for(int j=0;j<list.size()-1;j++){
int a=list[j].s,b=list[j+1].s;
g[a].push_back(b);
g[b].push_back(a);
}
}
return g;
}
class State{
public:
int n,b;
double cost;
State(int n,int b,double cost):n(n),b(b),cost(cost){}
bool operator<(State s)const{
return s.cost-cost<-eps;
}
};
Graph e;
vector<Point> vp;
Point a,b;
double getAngle(Vector v1,Vector v2){
double r=dot(v1,v2)/(abs(v1)*abs(v2));
if(r<-1.0)r=-1.0;
if(1.0<r)r=1.0;
return (acos(r)*180.0/pi);
}
double dijkstra(){
int s=0,g=0;
double d[MAX][MAX];
priority_queue<State> pq;
for(int i=0;i<vp.size();i++){
if(vp[i]==a)s=i;
if(vp[i]==b)g=i;
}
for(int i=0;i<MAX;i++)for(int j=0;j<MAX;j++)d[i][j]=inf;
for(int i=0;i<e[s].size();i++){
d[e[s][i]][s]=0;
pq.push(State(e[s][i],s,0));
}
while(pq.size()){
State u=pq.top();
pq.pop();
if(u.n==g)return u.cost;
if(d[u.n][u.b]-u.cost<-eps)continue;
for(int i=0;i<e[u.n].size();i++){
int next=e[u.n][i];
if(next==u.b)continue;
double cost=getAngle(vp[u.n]-vp[u.b],vp[next]-vp[u.n]);
if(u.cost+cost-d[next][u.n]<-eps){
d[next][u.n]=u.cost+cost;
pq.push(State(next,u.n,d[next][u.n]));
}
}
}
return -1;
}
int main()
{
int n;
while(1){
cin>>n;
if(n==0)break;
vector<Segment> vs;
for(int i=0;i<n;i++){
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
vs.push_back(Segment(Point(x1,y1),Point(x2,y2)));
}
cin>>a.x>>a.y>>b.x>>b.y;
vp.clear();
vp.push_back(a);
vp.push_back(b);
merge(vs);
e=SegmentArrangement(vs,vp);
double ans=dijkstra();
if(ans==-1)cout<<-1<<endl;
else printf("%.10f\n",dijkstra());
}
}
``` |
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <complex>
#include <vector>
#include <set>
#include <queue>
using namespace std;
typedef complex<double> P;
typedef pair<P,P> L;
typedef vector<vector<vector<double> > > mat;
const int INF = 1 << 29;
const double EPS = 1e-7;
namespace std{
bool operator == (const P &a, const P &b){
return fabs(real(a-b)) < EPS && fabs(imag(a-b)) < EPS;
}
}
struct data{
P p;
set<int> s;
data(P p):p(p){s.clear();}
};
struct state{
int prev,now;
double cost;
state(int p=0, int n=0, double c=0):prev(p),now(n),cost(c){}
bool operator < (const state &s) const {
return cost > s.cost;
}
};
int n;
L l[50];
P s, g;
vector<data> v;
mat cost;
double dot(P a, P b){ return real(conj(a)*b); }
double cross(P a, P b){ return imag(conj(a)*b); }
int ccw(P a, P b, P c){
b -= a;
c -= a;
if(cross(b,c) > EPS) return 1;
if(cross(b,c) < -EPS) return -1;
if(dot(b,c) < -EPS) return 2;
if(norm(b) < norm(c)) return -2;
return 0;
}
bool isIntersect(L s1, L s2){
return ( ccw(s1.first,s1.second,s2.first) * ccw(s1.first,s1.second,s2.second) <= 0 &&
ccw(s2.first,s2.second,s1.first) * ccw(s2.first,s2.second,s1.second) <= 0 );
}
P crossPoint(pair<P,P> l, pair<P,P> m){
double A = cross(l.second - l.first, m.second - m.first);
double B = cross(l.second - l.first, l.second - m.first);
if(fabs(A) < EPS && fabs(B) < EPS) return m.first;
else if(fabs(A) >= EPS) return m.first + B / A * (m.second - m.first);
}
void makeP(){
v.clear();
for(int i=0;i<n;i++){
bool f=false,f2=false;
for(int j=0;j<v.size();j++){
if(v[j].p == l[i].first){
v[j].s.insert(i);
f = true;
}
if(v[j].p == l[i].second){
v[j].s.insert(i);
f2 = true;
}
}
if(!f){
v.push_back(data(l[i].first));
v[v.size()-1].s.insert(i);
}
if(!f2){
v.push_back(data(l[i].second));
v[v.size()-1].s.insert(i);
}
for(int j=i+1;j<n;j++){
if(!isIntersect(l[i],l[j])) continue;
P p = crossPoint(l[i],l[j]);
f = false;
for(int k=0;k<v.size();k++){
if(v[k].p == p){
v[k].s.insert(i);
v[k].s.insert(j);
f = true;
break;
}
}
if(!f){
v.push_back(data(p));
v[v.size()-1].s.insert(i);
v[v.size()-1].s.insert(j);
}
}
}
}
double calcCost(P p1, P p2, P p3){
double A = abs(p2-p3);
double B = abs(p3-p1);
double C = abs(p1-p2);
return 180.0 - acos((B*B + C*C - A*A) / (2.0 * B * C)) * 180.0 / M_PI;
};
void makeCost(){
cost.assign(v.size(), vector<vector<double> >(v.size(), vector<double>(v.size(),(double)INF)));
for(int i=0;i<v.size();i++){
for(int j=0;j<v.size();j++){
if(i == j) continue;
bool f = false;
for(int k=0;k<n;k++){
if(v[i].s.find(k) != v[i].s.end() && v[j].s.find(k) != v[j].s.end()){
f = true;
break;
}
}
if(!f) continue;
for(int k=0;k<v.size();k++){
if(i == k || j == k) continue;
f = false;
for(int l=0;l<n;l++){
if(v[k].s.find(l) != v[k].s.end() && v[j].s.find(l) != v[j].s.end()){
f = true;
break;
}
}
if(f) cost[i][j][k] = calcCost(v[j].p, v[i].p, v[k].p);
}
}
}
}
void solve(){
priority_queue<state> Q;
state u,u2;
vector<vector<double> > d(v.size(), vector<double>(v.size(), (double)INF));
if(s == g){
//cout << 0 << endl;
//return;
}
for(int i=0;i<v.size();i++){
if(s == v[i].p){
u.prev = i;
break;
}
}
for(int i=0;i<v.size();i++){
for(set<int>::iterator it = v[u.prev].s.begin(); it != v[u.prev].s.end(); it++){
if(i != u.prev && v[i].s.find(*it) != v[i].s.end()){
u.now = i;
d[u.prev][i] = 0;
Q.push(u);
}
}
}
while(!Q.empty()){
u = Q.top();
Q.pop();
if(v[u.now].p == g){
printf("%.7f\n",u.cost);
return;
}
for(int i=0;i<v.size();i++){
u2 = state(u.now, i, d[u.prev][u.now] + cost[u.prev][u.now][i]);
if(u2.cost < d[u.now][i]){
d[u.now][i] = u2.cost;
Q.push(u2);
}
}
}
cout << -1 << endl;
}
int main(){
while(cin >> n && n){
double x,y,x2,y2;
for(int i=0;i<n;i++){
double x,y,x2,y2;
cin >> x >> y >> x2 >> y2;
l[i] = L(P(x,y),P(x2,y2));
}
cin >> x >> y >> x2 >> y2;
s = P(x,y);
g = P(x2,y2);
makeP();
makeCost();
solve();
}
} | ### Prompt
Develop a solution in CPP to the problem described below:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <complex>
#include <vector>
#include <set>
#include <queue>
using namespace std;
typedef complex<double> P;
typedef pair<P,P> L;
typedef vector<vector<vector<double> > > mat;
const int INF = 1 << 29;
const double EPS = 1e-7;
namespace std{
bool operator == (const P &a, const P &b){
return fabs(real(a-b)) < EPS && fabs(imag(a-b)) < EPS;
}
}
struct data{
P p;
set<int> s;
data(P p):p(p){s.clear();}
};
struct state{
int prev,now;
double cost;
state(int p=0, int n=0, double c=0):prev(p),now(n),cost(c){}
bool operator < (const state &s) const {
return cost > s.cost;
}
};
int n;
L l[50];
P s, g;
vector<data> v;
mat cost;
double dot(P a, P b){ return real(conj(a)*b); }
double cross(P a, P b){ return imag(conj(a)*b); }
int ccw(P a, P b, P c){
b -= a;
c -= a;
if(cross(b,c) > EPS) return 1;
if(cross(b,c) < -EPS) return -1;
if(dot(b,c) < -EPS) return 2;
if(norm(b) < norm(c)) return -2;
return 0;
}
bool isIntersect(L s1, L s2){
return ( ccw(s1.first,s1.second,s2.first) * ccw(s1.first,s1.second,s2.second) <= 0 &&
ccw(s2.first,s2.second,s1.first) * ccw(s2.first,s2.second,s1.second) <= 0 );
}
P crossPoint(pair<P,P> l, pair<P,P> m){
double A = cross(l.second - l.first, m.second - m.first);
double B = cross(l.second - l.first, l.second - m.first);
if(fabs(A) < EPS && fabs(B) < EPS) return m.first;
else if(fabs(A) >= EPS) return m.first + B / A * (m.second - m.first);
}
void makeP(){
v.clear();
for(int i=0;i<n;i++){
bool f=false,f2=false;
for(int j=0;j<v.size();j++){
if(v[j].p == l[i].first){
v[j].s.insert(i);
f = true;
}
if(v[j].p == l[i].second){
v[j].s.insert(i);
f2 = true;
}
}
if(!f){
v.push_back(data(l[i].first));
v[v.size()-1].s.insert(i);
}
if(!f2){
v.push_back(data(l[i].second));
v[v.size()-1].s.insert(i);
}
for(int j=i+1;j<n;j++){
if(!isIntersect(l[i],l[j])) continue;
P p = crossPoint(l[i],l[j]);
f = false;
for(int k=0;k<v.size();k++){
if(v[k].p == p){
v[k].s.insert(i);
v[k].s.insert(j);
f = true;
break;
}
}
if(!f){
v.push_back(data(p));
v[v.size()-1].s.insert(i);
v[v.size()-1].s.insert(j);
}
}
}
}
double calcCost(P p1, P p2, P p3){
double A = abs(p2-p3);
double B = abs(p3-p1);
double C = abs(p1-p2);
return 180.0 - acos((B*B + C*C - A*A) / (2.0 * B * C)) * 180.0 / M_PI;
};
void makeCost(){
cost.assign(v.size(), vector<vector<double> >(v.size(), vector<double>(v.size(),(double)INF)));
for(int i=0;i<v.size();i++){
for(int j=0;j<v.size();j++){
if(i == j) continue;
bool f = false;
for(int k=0;k<n;k++){
if(v[i].s.find(k) != v[i].s.end() && v[j].s.find(k) != v[j].s.end()){
f = true;
break;
}
}
if(!f) continue;
for(int k=0;k<v.size();k++){
if(i == k || j == k) continue;
f = false;
for(int l=0;l<n;l++){
if(v[k].s.find(l) != v[k].s.end() && v[j].s.find(l) != v[j].s.end()){
f = true;
break;
}
}
if(f) cost[i][j][k] = calcCost(v[j].p, v[i].p, v[k].p);
}
}
}
}
void solve(){
priority_queue<state> Q;
state u,u2;
vector<vector<double> > d(v.size(), vector<double>(v.size(), (double)INF));
if(s == g){
//cout << 0 << endl;
//return;
}
for(int i=0;i<v.size();i++){
if(s == v[i].p){
u.prev = i;
break;
}
}
for(int i=0;i<v.size();i++){
for(set<int>::iterator it = v[u.prev].s.begin(); it != v[u.prev].s.end(); it++){
if(i != u.prev && v[i].s.find(*it) != v[i].s.end()){
u.now = i;
d[u.prev][i] = 0;
Q.push(u);
}
}
}
while(!Q.empty()){
u = Q.top();
Q.pop();
if(v[u.now].p == g){
printf("%.7f\n",u.cost);
return;
}
for(int i=0;i<v.size();i++){
u2 = state(u.now, i, d[u.prev][u.now] + cost[u.prev][u.now][i]);
if(u2.cost < d[u.now][i]){
d[u.now][i] = u2.cost;
Q.push(u2);
}
}
}
cout << -1 << endl;
}
int main(){
while(cin >> n && n){
double x,y,x2,y2;
for(int i=0;i<n;i++){
double x,y,x2,y2;
cin >> x >> y >> x2 >> y2;
l[i] = L(P(x,y),P(x2,y2));
}
cin >> x >> y >> x2 >> y2;
s = P(x,y);
g = P(x2,y2);
makeP();
makeCost();
solve();
}
}
``` |
//Name: Kuru-Kuru Robot
//Level: 3
//Category: 幾何,Geometry,グラフ,Graph,線分アレンジメント,角度,練習問題
//Note:
/**
* 線分アレンジメントを行ってグラフを作る。
* 回転のコストを求めるためには、最後にたどった線分の角度を覚えておき、次にたどりたい線分の角度との差分を計算すればよい。
* これは、グラフを拡張して、(頂点,直前にいた頂点)を新しい頂点としたグラフにすれば実現できる。
* このグラフの上で、最短経路問題を解けば良い。
*
* 線分アレンジメントでは、最大で N(N-1) = O(N^2) 個の頂点が生成され得る。
* したがって、拡張後のグラフの頂点数は O(N^3)(各頂点について、最大2N本の辺が接続し得るため)。
* オーダーはO(N^4 log N)。
* (線分アレンジメントに O(N^2)、拡張後は各頂点が最大2N辺をもつため、辺数は O(N^4) となる)
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <queue>
using namespace std;
typedef complex<double> P;
const double EPS = 1e-9;
const double PI = acos(-1);
namespace std {
bool operator<(const P& a, const P& b)
{
if (fabs(a.real() - b.real()) < EPS) {
return a.imag() < b.imag();
} else {
return a.real() < b.real();
}
}
bool operator ==(const P& a, const P& b) {
return abs(a-b) < EPS;
}
};
struct Hash {
size_t operator()(const pair<int,int> &p) const {
return p.first * 2500 + p.second;
}
};
inline double dot(const P& a, const P& b) { return a.real()*b.real() + a.imag()*b.imag(); }
inline double cross(const P& a, const P& b) { return a.real()*b.imag() - b.real()*a.imag(); }
int ccw(const P& a, P b, P c)
{
b -= a;
c -= a;
if (cross(b, c) > EPS) { // ccw
return +1;
} else if (cross(b, c) < -EPS) { // cw
return -1;
} else if (dot(b, c) < -EPS) { // c-a-b or b-a-c
return +2;
} else if (dot(b, b) + EPS < dot(c, c)) { // a-b-c
return -2;
} else { // a-c-b
return 0;
}
}
struct segment/*{{{*/
{
P a, b;
segment() {}
segment(const P& x, const P& y) : a(x), b(y) {}
// AOJ 2402 Milkey Way
inline bool intersects(const segment& seg) const
{
return ccw(a, b, seg.a) * ccw(a, b, seg.b) <= 0
&& ccw(seg.a, seg.b, a) * ccw(seg.a, seg.b, b) <= 0;
}
// AOJ 1171 Laser Beam Relections
inline P intersection(const segment& ln) const
{
// assert(intersects(ln))
const P x = b - a;
const P y = ln.b - ln.a;
return a + x*(cross(y, ln.a - a))/cross(y, x);
}
};/*}}}*/
double calc_cost(const P &a, const P &b) {
double angle = arg(a) - arg(b);
while(angle < 0) angle += 2*PI;
while(angle > 2*PI) angle -= 2*PI;
return min(angle, 2*PI-angle);
}
bool solve() {
int N;
if(!(cin >> N)) return false;
if(!N) return false;
vector<segment> segments;
for(int i = 0; i < N; ++i) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
segments.emplace_back(P(x1, y1), P(x2, y2));
}
vector<P> nodes;
for(int i = 0; i < N; ++i) {
const segment &s1 = segments[i];
for(int j = 0; j < i; ++j) {
const segment &s2 = segments[j];
if(s1.intersects(s2)) {
nodes.push_back(s1.intersection(s2));
}
}
nodes.push_back(s1.a);
nodes.push_back(s1.b);
}
sort(begin(nodes), end(nodes));
nodes.erase(unique(begin(nodes), end(nodes)), end(nodes));
const int M = nodes.size();
vector<vector<int>> graph(nodes.size());
for(const segment &seg : segments) {
vector<pair<double,int>> ps;
for(int i = 0; i < M; ++i) {
if(ccw(seg.a, nodes[i], seg.b) == -2 || seg.a == nodes[i] || seg.b == nodes[i]) {
ps.emplace_back(abs(nodes[i] - seg.a), i);
}
}
sort(begin(ps), end(ps));
for(int i = 0; i+1 < ps.size(); ++i) {
graph[ps[i].second].push_back(ps[i+1].second);
graph[ps[i+1].second].push_back(ps[i].second);
}
}
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
const P sp(sx, sy), gp(gx, gy);
int start = -1, goal = -1;
for(int i = 0; i < M; ++i) {
if(nodes[i] == sp) {
start = i;
}
if(nodes[i] == gp) {
goal = i;
}
}
if(start == -1 || goal == -1) {
cout << "-1" << endl;
return true;
}
unordered_map<pair<int,int>, double, Hash> memo;
priority_queue<pair<double, pair<int,int>>> q;
q.push(make_pair(0, make_pair(-1, start)));
double ans = -1;
while(!q.empty()) {
const double cost = -q.top().first;
const int prev = q.top().second.first;
const int cur = q.top().second.second;
q.pop();
const auto key = make_pair(prev, cur);
if(memo[key] < cost) continue;
if(cur == goal) {
ans = cost;
break;
}
for(int next : graph[cur]) {
double nc = 0;
if(prev == -1) {
nc = 0;
} else {
const P v1 = nodes[cur] - nodes[prev];
const P v2 = nodes[next] - nodes[cur];
nc = cost + calc_cost(v1, v2);
}
const auto nkey = make_pair(cur, next);
if(!memo.count(nkey) || memo[nkey] > nc) {
memo[nkey] = nc;
q.push(make_pair(-nc, nkey));
}
}
}
if(ans < 0) cout << -1 << endl;
else cout << ans*180/PI << endl;
return true;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
cout.setf(ios::fixed);
cout.precision(10);
while(solve()) ;
return 0;
} | ### Prompt
In CPP, your task is to solve the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
//Name: Kuru-Kuru Robot
//Level: 3
//Category: 幾何,Geometry,グラフ,Graph,線分アレンジメント,角度,練習問題
//Note:
/**
* 線分アレンジメントを行ってグラフを作る。
* 回転のコストを求めるためには、最後にたどった線分の角度を覚えておき、次にたどりたい線分の角度との差分を計算すればよい。
* これは、グラフを拡張して、(頂点,直前にいた頂点)を新しい頂点としたグラフにすれば実現できる。
* このグラフの上で、最短経路問題を解けば良い。
*
* 線分アレンジメントでは、最大で N(N-1) = O(N^2) 個の頂点が生成され得る。
* したがって、拡張後のグラフの頂点数は O(N^3)(各頂点について、最大2N本の辺が接続し得るため)。
* オーダーはO(N^4 log N)。
* (線分アレンジメントに O(N^2)、拡張後は各頂点が最大2N辺をもつため、辺数は O(N^4) となる)
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <queue>
using namespace std;
typedef complex<double> P;
const double EPS = 1e-9;
const double PI = acos(-1);
namespace std {
bool operator<(const P& a, const P& b)
{
if (fabs(a.real() - b.real()) < EPS) {
return a.imag() < b.imag();
} else {
return a.real() < b.real();
}
}
bool operator ==(const P& a, const P& b) {
return abs(a-b) < EPS;
}
};
struct Hash {
size_t operator()(const pair<int,int> &p) const {
return p.first * 2500 + p.second;
}
};
inline double dot(const P& a, const P& b) { return a.real()*b.real() + a.imag()*b.imag(); }
inline double cross(const P& a, const P& b) { return a.real()*b.imag() - b.real()*a.imag(); }
int ccw(const P& a, P b, P c)
{
b -= a;
c -= a;
if (cross(b, c) > EPS) { // ccw
return +1;
} else if (cross(b, c) < -EPS) { // cw
return -1;
} else if (dot(b, c) < -EPS) { // c-a-b or b-a-c
return +2;
} else if (dot(b, b) + EPS < dot(c, c)) { // a-b-c
return -2;
} else { // a-c-b
return 0;
}
}
struct segment/*{{{*/
{
P a, b;
segment() {}
segment(const P& x, const P& y) : a(x), b(y) {}
// AOJ 2402 Milkey Way
inline bool intersects(const segment& seg) const
{
return ccw(a, b, seg.a) * ccw(a, b, seg.b) <= 0
&& ccw(seg.a, seg.b, a) * ccw(seg.a, seg.b, b) <= 0;
}
// AOJ 1171 Laser Beam Relections
inline P intersection(const segment& ln) const
{
// assert(intersects(ln))
const P x = b - a;
const P y = ln.b - ln.a;
return a + x*(cross(y, ln.a - a))/cross(y, x);
}
};/*}}}*/
double calc_cost(const P &a, const P &b) {
double angle = arg(a) - arg(b);
while(angle < 0) angle += 2*PI;
while(angle > 2*PI) angle -= 2*PI;
return min(angle, 2*PI-angle);
}
bool solve() {
int N;
if(!(cin >> N)) return false;
if(!N) return false;
vector<segment> segments;
for(int i = 0; i < N; ++i) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
segments.emplace_back(P(x1, y1), P(x2, y2));
}
vector<P> nodes;
for(int i = 0; i < N; ++i) {
const segment &s1 = segments[i];
for(int j = 0; j < i; ++j) {
const segment &s2 = segments[j];
if(s1.intersects(s2)) {
nodes.push_back(s1.intersection(s2));
}
}
nodes.push_back(s1.a);
nodes.push_back(s1.b);
}
sort(begin(nodes), end(nodes));
nodes.erase(unique(begin(nodes), end(nodes)), end(nodes));
const int M = nodes.size();
vector<vector<int>> graph(nodes.size());
for(const segment &seg : segments) {
vector<pair<double,int>> ps;
for(int i = 0; i < M; ++i) {
if(ccw(seg.a, nodes[i], seg.b) == -2 || seg.a == nodes[i] || seg.b == nodes[i]) {
ps.emplace_back(abs(nodes[i] - seg.a), i);
}
}
sort(begin(ps), end(ps));
for(int i = 0; i+1 < ps.size(); ++i) {
graph[ps[i].second].push_back(ps[i+1].second);
graph[ps[i+1].second].push_back(ps[i].second);
}
}
int sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
const P sp(sx, sy), gp(gx, gy);
int start = -1, goal = -1;
for(int i = 0; i < M; ++i) {
if(nodes[i] == sp) {
start = i;
}
if(nodes[i] == gp) {
goal = i;
}
}
if(start == -1 || goal == -1) {
cout << "-1" << endl;
return true;
}
unordered_map<pair<int,int>, double, Hash> memo;
priority_queue<pair<double, pair<int,int>>> q;
q.push(make_pair(0, make_pair(-1, start)));
double ans = -1;
while(!q.empty()) {
const double cost = -q.top().first;
const int prev = q.top().second.first;
const int cur = q.top().second.second;
q.pop();
const auto key = make_pair(prev, cur);
if(memo[key] < cost) continue;
if(cur == goal) {
ans = cost;
break;
}
for(int next : graph[cur]) {
double nc = 0;
if(prev == -1) {
nc = 0;
} else {
const P v1 = nodes[cur] - nodes[prev];
const P v2 = nodes[next] - nodes[cur];
nc = cost + calc_cost(v1, v2);
}
const auto nkey = make_pair(cur, next);
if(!memo.count(nkey) || memo[nkey] > nc) {
memo[nkey] = nc;
q.push(make_pair(-nc, nkey));
}
}
}
if(ans < 0) cout << -1 << endl;
else cout << ans*180/PI << endl;
return true;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
cout.setf(ios::fixed);
cout.precision(10);
while(solve()) ;
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
using Real = double;
using Point = complex< Real >;
const Real EPS = 1e-8, PI = acos(-1);
inline bool eq(Real a, Real b) { return fabs(b - a) < EPS; }
Point operator*(const Point &p, const Real &d) {
return Point(real(p) * d, imag(p) * d);
}
istream &operator>>(istream &is, Point &p) {
Real a, b;
is >> a >> b;
p = Point(a, b);
return is;
}
ostream &operator<<(ostream &os, Point &p) {
os << fixed << setprecision(10) << p.real() << " " << p.imag();
}
Point rotate(Real theta, const Point &p) {
return Point(cos(theta) * p.real() - sin(theta) * p.imag(), sin(theta) * p.real() + cos(theta) * p.imag());
}
Real radian_to_degree(Real r) {
return (r * 180.0 / PI);
}
Real degree_to_radian(Real d) {
return (d * PI / 180.0);
}
Real get_angle(const Point &a, const Point &b, const Point &c) {
const Point v(b - a), w(c - b);
Real alpha = atan2(v.imag(), v.real()), beta = atan2(w.imag(), w.real());
if(alpha > beta) swap(alpha, beta);
Real theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
namespace std {
bool operator<(const Point &a, const Point &b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
}
struct Line {
Point a, b;
Line() = default;
Line(Point a, Point b) : a(a), b(b) {}
Line(Real A, Real B, Real C) // Ax + By = C
{
if(eq(A, 0)) a = Point(0, C / B), b = Point(1, C / B);
else if(eq(B, 0)) b = Point(C / A, 0), b = Point(C / A, 1);
else a = Point(0, C / B), b = Point(C / A, 0);
}
friend ostream &operator<<(ostream &os, Line &p) {
return os << p.a << " to " << p.b;
}
friend istream &operator>>(istream &is, Line &a) {
return is >> a.a >> a.b;
}
};
struct Segment : Line {
Segment() = default;
Segment(Point a, Point b) : Line(a, b) {}
};
struct Circle {
Point p;
Real r;
Circle() = default;
Circle(Point p, Real r) : p(p), r(r) {}
};
using Points = vector< Point >;
using Polygon = vector< Point >;
using Segments = vector< Segment >;
using Lines = vector< Line >;
using Circles = vector< Circle >;
Real cross(const Point &a, const Point &b) {
return real(a) * imag(b) - imag(a) * real(b);
}
Real dot(const Point &a, const Point &b) {
return real(a) * real(b) + imag(a) * imag(b);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C
int ccw(const Point &a, Point b, Point c) {
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1; // "COUNTER_CLOCKWISE"
if(cross(b, c) < -EPS) return -1; // "CLOCKWISE"
if(dot(b, c) < 0) return +2; // "ONLINE_BACK"
if(norm(b) < norm(c)) return -2; // "ONLINE_FRONT"
return 0; // "ON_SEGMENT"
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool parallel(const Line &a, const Line &b) {
return eq(cross(a.b - a.a, b.b - b.a), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool orthogonal(const Line &a, const Line &b) {
return eq(dot(a.a - a.b, b.a - b.b), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A
Point projection(const Line &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
Point projection(const Segment &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B
Point reflection(const Line &l, const Point &p) {
return p + (projection(l, p) - p) * 2.0;
}
bool intersect(const Line &l, const Point &p) {
return abs(ccw(l.a, l.b, p)) != 1;
}
bool intersect(const Line &l, const Line &m) {
return abs(cross(l.b - l.a, m.b - m.a)) > EPS || abs(cross(l.b - l.a, m.b - l.a)) < EPS;
}
bool intersect(const Segment &s, const Point &p) {
return ccw(s.a, s.b, p) == 0;
}
bool intersect(const Line &l, const Segment &s) {
return cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < EPS;
}
Real distance(const Line &l, const Point &p);
bool intersect(const Circle &c, const Line &l) {
return distance(l, c.p) <= c.r + EPS;
}
bool intersect(const Circle &c, const Point &p) {
return abs(abs(p - c.p) - c.r) < EPS;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B
bool intersect(const Segment &s, const Segment &t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 && ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
int intersect(const Circle &c, const Segment &l) {
if(norm(projection(l, c.p) - c.p) - c.r * c.r > EPS) return 0;
auto d1 = abs(c.p - l.a), d2 = abs(c.p - l.b);
if(d1 < c.r + EPS && d2 < c.r + EPS) return 0;
if(d1 < c.r - EPS && d2 > c.r + EPS || d1 > c.r + EPS && d2 < c.r - EPS) return 1;
const Point h = projection(l, c.p);
if(dot(l.a - h, l.b - h) < 0) return 2;
return 0;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=jp
int intersect(Circle c1, Circle c2) {
if(c1.r < c2.r) swap(c1, c2);
Real d = abs(c1.p - c2.p);
if(c1.r + c2.r < d) return 4;
if(eq(c1.r + c2.r, d)) return 3;
if(c1.r - c2.r < d) return 2;
if(eq(c1.r - c2.r, d)) return 1;
return 0;
}
Real distance(const Point &a, const Point &b) {
return abs(a - b);
}
Real distance(const Line &l, const Point &p) {
return abs(p - projection(l, p));
}
Real distance(const Line &l, const Line &m) {
return intersect(l, m) ? 0 : distance(l, m.a);
}
Real distance(const Segment &s, const Point &p) {
Point r = projection(s, p);
if(intersect(s, r)) return abs(r - p);
return min(abs(s.a - p), abs(s.b - p));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D
Real distance(const Segment &a, const Segment &b) {
if(intersect(a, b)) return 0;
return min({distance(a, b.a), distance(a, b.b), distance(b, a.a), distance(b, a.b)});
}
Real distance(const Line &l, const Segment &s) {
if(intersect(l, s)) return 0;
return min(distance(l, s.a), distance(l, s.b));
}
Point crosspoint(const Line &l, const Line &m) {
Real A = cross(l.b - l.a, m.b - m.a);
Real B = cross(l.b - l.a, l.b - m.a);
if(eq(abs(A), 0.0) && eq(abs(B), 0.0)) return m.a;
return m.a + (m.b - m.a) * B / A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C
Point crosspoint(const Segment &l, const Segment &m) {
return crosspoint(Line(l), Line(m));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D
pair< Point, Point > crosspoint(const Circle &c, const Line l) {
Point pr = projection(l, c.p);
Point e = (l.b - l.a) / abs(l.b - l.a);
if(eq(distance(l, c.p), c.r)) return {pr, pr};
double base = sqrt(c.r * c.r - norm(pr - c.p));
return {pr - e * base, pr + e * base};
}
pair< Point, Point > crosspoint(const Circle &c, const Segment &l) {
Line aa = Line(l.a, l.b);
if(intersect(c, l) == 2) return crosspoint(c, aa);
auto ret = crosspoint(c, aa);
if(dot(l.a - ret.first, l.b - ret.first) < 0) ret.second = ret.first;
else ret.first = ret.second;
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E
pair< Point, Point > crosspoint(const Circle &c1, const Circle &c2) {
Real d = abs(c1.p - c2.p);
Real a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));
Real t = atan2(c2.p.imag() - c1.p.imag(), c2.p.real() - c1.p.real());
Point p1 = c1.p + Point(cos(t + a) * c1.r, sin(t + a) * c1.r);
Point p2 = c1.p + Point(cos(t - a) * c1.r, sin(t - a) * c1.r);
return {p1, p2};
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_F
pair< Point, Point > tangent(const Circle &c1, const Point &p2) {
return crosspoint(c1, Circle(p2, sqrt(norm(c1.p - p2) - c1.r * c1.r)));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_G
Lines tangent(Circle c1, Circle c2) {
Lines ret;
if(c1.r < c2.r) swap(c1, c2);
Real g = norm(c1.p - c2.p);
if(eq(g, 0)) return ret;
Point u = (c2.p - c1.p) / sqrt(g);
Point v = rotate(PI * 0.5, u);
for(int s : {-1, 1}) {
Real h = (c1.r + s * c2.r) / sqrt(g);
if(eq(1 - h * h, 0)) {
ret.emplace_back(c1.p + u * c1.r, c1.p + (u + v) * c1.r);
} else if(1 - h * h > 0) {
Point uu = u * h, vv = v * sqrt(1 - h * h);
ret.emplace_back(c1.p + (uu + vv) * c1.r, c2.p - (uu + vv) * c2.r * s);
ret.emplace_back(c1.p + (uu - vv) * c1.r, c2.p - (uu - vv) * c2.r * s);
}
}
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B
bool is_convex(const Polygon &p) {
int n = (int) p.size();
for(int i = 0; i < n; i++) {
if(ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == -1) return false;
}
return true;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A
Polygon convex_hull(Polygon &p) {
int n = (int) p.size(), k = 0;
if(n <= 2) return p;
sort(p.begin(), p.end());
vector< Point > ch(2 * n);
for(int i = 0; i < n; ch[k++] = p[i++]) {
while(k >= 2 && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {
while(k >= t && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
ch.resize(k - 1);
return ch;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C
enum {
OUT, ON, IN
};
int contains(const Polygon &Q, const Point &p) {
bool in = false;
for(int i = 0; i < Q.size(); i++) {
Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;
if(a.imag() > b.imag()) swap(a, b);
if(a.imag() <= 0 && 0 < b.imag() && cross(a, b) < 0) in = !in;
if(cross(a, b) == 0 && dot(a, b) <= 0) return ON;
}
return in ? IN : OUT;
}
bool merge_if_able(Segment &s1, const Segment &s2) {
if(abs(cross(s1.b - s1.a, s2.b - s2.a)) > EPS) return false;
if(ccw(s1.a, s2.a, s1.b) == 1 || ccw(s1.a, s2.a, s1.b) == -1) return false;
if(ccw(s1.a, s1.b, s2.a) == -2 || ccw(s2.a, s2.b, s1.a) == -2) return false;
s1 = Segment(min(s1.a, s2.a), max(s1.b, s2.b));
return true;
}
void merge_segments(vector< Segment > &segs) {
for(int i = 0; i < segs.size(); i++) {
if(segs[i].b < segs[i].a) swap(segs[i].a, segs[i].b);
}
for(int i = 0; i < segs.size(); i++) {
for(int j = i + 1; j < segs.size(); j++) {
if(merge_if_able(segs[i], segs[j])) {
segs[j--] = segs.back(), segs.pop_back();
}
}
}
}
vector< vector< int > > segment_arrangement(vector< Segment > &segs, vector< Point > &ps) {
vector< vector< int > > g;
int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(intersect(segs[i], segs[j])) {
ps.emplace_back(crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C
Polygon convex_cut(const Polygon &U, Line l) {
Polygon ret;
for(int i = 0; i < U.size(); i++) {
Point now = U[i], nxt = U[(i + 1) % U.size()];
if(ccw(l.a, l.b, now) != -1) ret.push_back(now);
if(ccw(l.a, l.b, now) * ccw(l.a, l.b, nxt) < 0) {
ret.push_back(crosspoint(Line(now, nxt), l));
}
}
return (ret);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A
Real area2(const Polygon &p) {
Real A = 0;
for(int i = 0; i < p.size(); ++i) {
A += cross(p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_H
Real area2(const Polygon &p, const Circle &c) {
if(p.size() < 3) return 0.0;
function< Real(Circle, Point, Point) > cross_area = [&](const Circle &c, const Point &a, const Point &b) {
Point va = c.p - a, vb = c.p - b;
Real f = cross(va, vb), ret = 0.0;
if(eq(f, 0.0)) return ret;
if(max(abs(va), abs(vb)) < c.r + EPS) return f;
if(distance(Segment(a, b), c.p) > c.r - EPS) return c.r * c.r * arg(vb * conj(va));
auto u = crosspoint(c, Segment(a, b));
vector< Point > tot{a, u.first, u.second, b};
for(int i = 0; i + 1 < tot.size(); i++) {
ret += cross_area(c, tot[i], tot[i + 1]);
}
return ret;
};
Real A = 0;
for(int i = 0; i < p.size(); i++) {
A += cross_area(c, p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B
Real convex_diameter(const Polygon &p) {
int N = (int) p.size();
int is = 0, js = 0;
for(int i = 1; i < N; i++) {
if(p[i].imag() > p[is].imag()) is = i;
if(p[i].imag() < p[js].imag()) js = i;
}
Real maxdis = norm(p[is] - p[js]);
int maxi, maxj, i, j;
i = maxi = is;
j = maxj = js;
do {
if(cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {
j = (j + 1) % N;
} else {
i = (i + 1) % N;
}
if(norm(p[i] - p[j]) > maxdis) {
maxdis = norm(p[i] - p[j]);
maxi = i;
maxj = j;
}
} while(i != is || j != js);
return sqrt(maxdis);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A
Real closest_pair(Points ps) {
if(ps.size() <= 1) throw (0);
sort(begin(ps), end(ps));
auto compare_y = [&](const Point &a, const Point &b) {
return imag(a) < imag(b);
};
vector< Point > beet(ps.size());
const Real INF = 1e18;
function< Real(int, int) > rec = [&](int left, int right) {
if(right - left <= 1) return INF;
int mid = (left + right) >> 1;
auto x = real(ps[mid]);
auto ret = min(rec(left, mid), rec(mid, right));
inplace_merge(begin(ps) + left, begin(ps) + mid, begin(ps) + right, compare_y);
int ptr = 0;
for(int i = left; i < right; i++) {
if(abs(real(ps[i]) - x) >= ret) continue;
for(int j = 0; j < ptr; j++) {
auto luz = ps[i] - beet[ptr - j - 1];
if(imag(luz) >= ret) break;
ret = min(ret, abs(luz));
}
beet[ptr++] = ps[i];
}
return ret;
};
return rec(0, (int) ps.size());
}
const Real INF = 1e18;
double GetAngle(const Point &a, const Point &b, const Point &c) {
const Point v = b - a, w = c - b;
double alpha = atan2(imag(v), real(v)), beta = atan2(imag(w), real(w));
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180.0 / PI;
return min(theta, 360.0 - theta);
}
Real dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps) {
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< Real > > min_cost(g.size(), vector< Real >(g.size(), INF));
typedef tuple< Real, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
double cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + GetAngle(ps[pre], ps[cur], ps[to]);
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main() {
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
auto g = segment_arrangement(segs, ps);
double ret = dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
}
| ### Prompt
Create a solution in cpp for the following problem:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
using Real = double;
using Point = complex< Real >;
const Real EPS = 1e-8, PI = acos(-1);
inline bool eq(Real a, Real b) { return fabs(b - a) < EPS; }
Point operator*(const Point &p, const Real &d) {
return Point(real(p) * d, imag(p) * d);
}
istream &operator>>(istream &is, Point &p) {
Real a, b;
is >> a >> b;
p = Point(a, b);
return is;
}
ostream &operator<<(ostream &os, Point &p) {
os << fixed << setprecision(10) << p.real() << " " << p.imag();
}
Point rotate(Real theta, const Point &p) {
return Point(cos(theta) * p.real() - sin(theta) * p.imag(), sin(theta) * p.real() + cos(theta) * p.imag());
}
Real radian_to_degree(Real r) {
return (r * 180.0 / PI);
}
Real degree_to_radian(Real d) {
return (d * PI / 180.0);
}
Real get_angle(const Point &a, const Point &b, const Point &c) {
const Point v(b - a), w(c - b);
Real alpha = atan2(v.imag(), v.real()), beta = atan2(w.imag(), w.real());
if(alpha > beta) swap(alpha, beta);
Real theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
namespace std {
bool operator<(const Point &a, const Point &b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
}
struct Line {
Point a, b;
Line() = default;
Line(Point a, Point b) : a(a), b(b) {}
Line(Real A, Real B, Real C) // Ax + By = C
{
if(eq(A, 0)) a = Point(0, C / B), b = Point(1, C / B);
else if(eq(B, 0)) b = Point(C / A, 0), b = Point(C / A, 1);
else a = Point(0, C / B), b = Point(C / A, 0);
}
friend ostream &operator<<(ostream &os, Line &p) {
return os << p.a << " to " << p.b;
}
friend istream &operator>>(istream &is, Line &a) {
return is >> a.a >> a.b;
}
};
struct Segment : Line {
Segment() = default;
Segment(Point a, Point b) : Line(a, b) {}
};
struct Circle {
Point p;
Real r;
Circle() = default;
Circle(Point p, Real r) : p(p), r(r) {}
};
using Points = vector< Point >;
using Polygon = vector< Point >;
using Segments = vector< Segment >;
using Lines = vector< Line >;
using Circles = vector< Circle >;
Real cross(const Point &a, const Point &b) {
return real(a) * imag(b) - imag(a) * real(b);
}
Real dot(const Point &a, const Point &b) {
return real(a) * real(b) + imag(a) * imag(b);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C
int ccw(const Point &a, Point b, Point c) {
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1; // "COUNTER_CLOCKWISE"
if(cross(b, c) < -EPS) return -1; // "CLOCKWISE"
if(dot(b, c) < 0) return +2; // "ONLINE_BACK"
if(norm(b) < norm(c)) return -2; // "ONLINE_FRONT"
return 0; // "ON_SEGMENT"
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool parallel(const Line &a, const Line &b) {
return eq(cross(a.b - a.a, b.b - b.a), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool orthogonal(const Line &a, const Line &b) {
return eq(dot(a.a - a.b, b.a - b.b), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A
Point projection(const Line &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
Point projection(const Segment &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B
Point reflection(const Line &l, const Point &p) {
return p + (projection(l, p) - p) * 2.0;
}
bool intersect(const Line &l, const Point &p) {
return abs(ccw(l.a, l.b, p)) != 1;
}
bool intersect(const Line &l, const Line &m) {
return abs(cross(l.b - l.a, m.b - m.a)) > EPS || abs(cross(l.b - l.a, m.b - l.a)) < EPS;
}
bool intersect(const Segment &s, const Point &p) {
return ccw(s.a, s.b, p) == 0;
}
bool intersect(const Line &l, const Segment &s) {
return cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < EPS;
}
Real distance(const Line &l, const Point &p);
bool intersect(const Circle &c, const Line &l) {
return distance(l, c.p) <= c.r + EPS;
}
bool intersect(const Circle &c, const Point &p) {
return abs(abs(p - c.p) - c.r) < EPS;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B
bool intersect(const Segment &s, const Segment &t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 && ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
int intersect(const Circle &c, const Segment &l) {
if(norm(projection(l, c.p) - c.p) - c.r * c.r > EPS) return 0;
auto d1 = abs(c.p - l.a), d2 = abs(c.p - l.b);
if(d1 < c.r + EPS && d2 < c.r + EPS) return 0;
if(d1 < c.r - EPS && d2 > c.r + EPS || d1 > c.r + EPS && d2 < c.r - EPS) return 1;
const Point h = projection(l, c.p);
if(dot(l.a - h, l.b - h) < 0) return 2;
return 0;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=jp
int intersect(Circle c1, Circle c2) {
if(c1.r < c2.r) swap(c1, c2);
Real d = abs(c1.p - c2.p);
if(c1.r + c2.r < d) return 4;
if(eq(c1.r + c2.r, d)) return 3;
if(c1.r - c2.r < d) return 2;
if(eq(c1.r - c2.r, d)) return 1;
return 0;
}
Real distance(const Point &a, const Point &b) {
return abs(a - b);
}
Real distance(const Line &l, const Point &p) {
return abs(p - projection(l, p));
}
Real distance(const Line &l, const Line &m) {
return intersect(l, m) ? 0 : distance(l, m.a);
}
Real distance(const Segment &s, const Point &p) {
Point r = projection(s, p);
if(intersect(s, r)) return abs(r - p);
return min(abs(s.a - p), abs(s.b - p));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D
Real distance(const Segment &a, const Segment &b) {
if(intersect(a, b)) return 0;
return min({distance(a, b.a), distance(a, b.b), distance(b, a.a), distance(b, a.b)});
}
Real distance(const Line &l, const Segment &s) {
if(intersect(l, s)) return 0;
return min(distance(l, s.a), distance(l, s.b));
}
Point crosspoint(const Line &l, const Line &m) {
Real A = cross(l.b - l.a, m.b - m.a);
Real B = cross(l.b - l.a, l.b - m.a);
if(eq(abs(A), 0.0) && eq(abs(B), 0.0)) return m.a;
return m.a + (m.b - m.a) * B / A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C
Point crosspoint(const Segment &l, const Segment &m) {
return crosspoint(Line(l), Line(m));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D
pair< Point, Point > crosspoint(const Circle &c, const Line l) {
Point pr = projection(l, c.p);
Point e = (l.b - l.a) / abs(l.b - l.a);
if(eq(distance(l, c.p), c.r)) return {pr, pr};
double base = sqrt(c.r * c.r - norm(pr - c.p));
return {pr - e * base, pr + e * base};
}
pair< Point, Point > crosspoint(const Circle &c, const Segment &l) {
Line aa = Line(l.a, l.b);
if(intersect(c, l) == 2) return crosspoint(c, aa);
auto ret = crosspoint(c, aa);
if(dot(l.a - ret.first, l.b - ret.first) < 0) ret.second = ret.first;
else ret.first = ret.second;
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E
pair< Point, Point > crosspoint(const Circle &c1, const Circle &c2) {
Real d = abs(c1.p - c2.p);
Real a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));
Real t = atan2(c2.p.imag() - c1.p.imag(), c2.p.real() - c1.p.real());
Point p1 = c1.p + Point(cos(t + a) * c1.r, sin(t + a) * c1.r);
Point p2 = c1.p + Point(cos(t - a) * c1.r, sin(t - a) * c1.r);
return {p1, p2};
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_F
pair< Point, Point > tangent(const Circle &c1, const Point &p2) {
return crosspoint(c1, Circle(p2, sqrt(norm(c1.p - p2) - c1.r * c1.r)));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_G
Lines tangent(Circle c1, Circle c2) {
Lines ret;
if(c1.r < c2.r) swap(c1, c2);
Real g = norm(c1.p - c2.p);
if(eq(g, 0)) return ret;
Point u = (c2.p - c1.p) / sqrt(g);
Point v = rotate(PI * 0.5, u);
for(int s : {-1, 1}) {
Real h = (c1.r + s * c2.r) / sqrt(g);
if(eq(1 - h * h, 0)) {
ret.emplace_back(c1.p + u * c1.r, c1.p + (u + v) * c1.r);
} else if(1 - h * h > 0) {
Point uu = u * h, vv = v * sqrt(1 - h * h);
ret.emplace_back(c1.p + (uu + vv) * c1.r, c2.p - (uu + vv) * c2.r * s);
ret.emplace_back(c1.p + (uu - vv) * c1.r, c2.p - (uu - vv) * c2.r * s);
}
}
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B
bool is_convex(const Polygon &p) {
int n = (int) p.size();
for(int i = 0; i < n; i++) {
if(ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == -1) return false;
}
return true;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A
Polygon convex_hull(Polygon &p) {
int n = (int) p.size(), k = 0;
if(n <= 2) return p;
sort(p.begin(), p.end());
vector< Point > ch(2 * n);
for(int i = 0; i < n; ch[k++] = p[i++]) {
while(k >= 2 && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {
while(k >= t && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
ch.resize(k - 1);
return ch;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C
enum {
OUT, ON, IN
};
int contains(const Polygon &Q, const Point &p) {
bool in = false;
for(int i = 0; i < Q.size(); i++) {
Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;
if(a.imag() > b.imag()) swap(a, b);
if(a.imag() <= 0 && 0 < b.imag() && cross(a, b) < 0) in = !in;
if(cross(a, b) == 0 && dot(a, b) <= 0) return ON;
}
return in ? IN : OUT;
}
bool merge_if_able(Segment &s1, const Segment &s2) {
if(abs(cross(s1.b - s1.a, s2.b - s2.a)) > EPS) return false;
if(ccw(s1.a, s2.a, s1.b) == 1 || ccw(s1.a, s2.a, s1.b) == -1) return false;
if(ccw(s1.a, s1.b, s2.a) == -2 || ccw(s2.a, s2.b, s1.a) == -2) return false;
s1 = Segment(min(s1.a, s2.a), max(s1.b, s2.b));
return true;
}
void merge_segments(vector< Segment > &segs) {
for(int i = 0; i < segs.size(); i++) {
if(segs[i].b < segs[i].a) swap(segs[i].a, segs[i].b);
}
for(int i = 0; i < segs.size(); i++) {
for(int j = i + 1; j < segs.size(); j++) {
if(merge_if_able(segs[i], segs[j])) {
segs[j--] = segs.back(), segs.pop_back();
}
}
}
}
vector< vector< int > > segment_arrangement(vector< Segment > &segs, vector< Point > &ps) {
vector< vector< int > > g;
int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(intersect(segs[i], segs[j])) {
ps.emplace_back(crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C
Polygon convex_cut(const Polygon &U, Line l) {
Polygon ret;
for(int i = 0; i < U.size(); i++) {
Point now = U[i], nxt = U[(i + 1) % U.size()];
if(ccw(l.a, l.b, now) != -1) ret.push_back(now);
if(ccw(l.a, l.b, now) * ccw(l.a, l.b, nxt) < 0) {
ret.push_back(crosspoint(Line(now, nxt), l));
}
}
return (ret);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A
Real area2(const Polygon &p) {
Real A = 0;
for(int i = 0; i < p.size(); ++i) {
A += cross(p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_H
Real area2(const Polygon &p, const Circle &c) {
if(p.size() < 3) return 0.0;
function< Real(Circle, Point, Point) > cross_area = [&](const Circle &c, const Point &a, const Point &b) {
Point va = c.p - a, vb = c.p - b;
Real f = cross(va, vb), ret = 0.0;
if(eq(f, 0.0)) return ret;
if(max(abs(va), abs(vb)) < c.r + EPS) return f;
if(distance(Segment(a, b), c.p) > c.r - EPS) return c.r * c.r * arg(vb * conj(va));
auto u = crosspoint(c, Segment(a, b));
vector< Point > tot{a, u.first, u.second, b};
for(int i = 0; i + 1 < tot.size(); i++) {
ret += cross_area(c, tot[i], tot[i + 1]);
}
return ret;
};
Real A = 0;
for(int i = 0; i < p.size(); i++) {
A += cross_area(c, p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B
Real convex_diameter(const Polygon &p) {
int N = (int) p.size();
int is = 0, js = 0;
for(int i = 1; i < N; i++) {
if(p[i].imag() > p[is].imag()) is = i;
if(p[i].imag() < p[js].imag()) js = i;
}
Real maxdis = norm(p[is] - p[js]);
int maxi, maxj, i, j;
i = maxi = is;
j = maxj = js;
do {
if(cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {
j = (j + 1) % N;
} else {
i = (i + 1) % N;
}
if(norm(p[i] - p[j]) > maxdis) {
maxdis = norm(p[i] - p[j]);
maxi = i;
maxj = j;
}
} while(i != is || j != js);
return sqrt(maxdis);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A
Real closest_pair(Points ps) {
if(ps.size() <= 1) throw (0);
sort(begin(ps), end(ps));
auto compare_y = [&](const Point &a, const Point &b) {
return imag(a) < imag(b);
};
vector< Point > beet(ps.size());
const Real INF = 1e18;
function< Real(int, int) > rec = [&](int left, int right) {
if(right - left <= 1) return INF;
int mid = (left + right) >> 1;
auto x = real(ps[mid]);
auto ret = min(rec(left, mid), rec(mid, right));
inplace_merge(begin(ps) + left, begin(ps) + mid, begin(ps) + right, compare_y);
int ptr = 0;
for(int i = left; i < right; i++) {
if(abs(real(ps[i]) - x) >= ret) continue;
for(int j = 0; j < ptr; j++) {
auto luz = ps[i] - beet[ptr - j - 1];
if(imag(luz) >= ret) break;
ret = min(ret, abs(luz));
}
beet[ptr++] = ps[i];
}
return ret;
};
return rec(0, (int) ps.size());
}
const Real INF = 1e18;
double GetAngle(const Point &a, const Point &b, const Point &c) {
const Point v = b - a, w = c - b;
double alpha = atan2(imag(v), real(v)), beta = atan2(imag(w), real(w));
if(alpha > beta) swap(alpha, beta);
double theta = (beta - alpha) * 180.0 / PI;
return min(theta, 360.0 - theta);
}
Real dijkstra(vector< vector< int > > &g, Point &s, Point &t, vector< Point > &ps) {
int idx;
for(int i = 0; i < ps.size(); i++) {
if(ps[i] == s) idx = i;
}
vector< vector< Real > > min_cost(g.size(), vector< Real >(g.size(), INF));
typedef tuple< Real, int, int > State;
priority_queue< State, vector< State >, greater< State > > que;
for(auto &to : g[idx]) {
que.emplace(0, idx, to);
min_cost[idx][to] = 0.0;
}
while(!que.empty()) {
double cost;
int pre, cur;
tie(cost, pre, cur) = que.top();
que.pop();
if(cost > min_cost[pre][cur]) continue;
if(ps[cur] == t) return (cost);
for(auto &to : g[cur]) {
if(pre == to) continue;
double ncost = cost + GetAngle(ps[pre], ps[cur], ps[to]);
if(ncost < min_cost[cur][to]) {
min_cost[cur][to] = ncost;
que.emplace(ncost, cur, to);
}
}
}
return INF;
}
int main() {
int N;
while(scanf("%d", &N), N) {
vector< Segment > segs(N);
Point S, T;
for(auto &s : segs) cin >> s;
cin >> S >> T;
vector< Point > ps;
auto g = segment_arrangement(segs, ps);
double ret = dijkstra(g, S, T, ps);
if(ret >= INF) cout << -1 << endl;
else cout << fixed << setprecision(12) << ret << endl;
}
}
``` |
#include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
#include <map>
#include <queue>
using namespace std;
const double EPS = 1e-10;
const double INF = 1e12;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<double> P;
typedef vector<P> VP;
struct L : array<P, 2>{
L(const P& a, const P& b){ at(0)=a; at(1)=b; }
L(){}
};
namespace std{
bool operator < (const P& a, const P& b){
return !EQ(a.X,b.X) ? a.X<b.X : a.Y+EPS<b.Y;
}
bool operator == (const P& a, const P& b){
return abs(a-b) < EPS;
}
}
double dot(P a, P b){
return (conj(a)*b).X;
}
double cross(P a, P b){
return (conj(a)*b).Y;
}
int ccw(P a, P b, P c){
b -= a;
c -= a;
if(cross(b,c) > EPS) return +1; //ccw
if(cross(b,c) < -EPS) return -1; //cw
if(dot(b,c) < -EPS) return +2; //c-a-b
if(abs(c)-abs(b) > EPS) return -2; //a-b-c
return 0; //a-c-b
}
bool intersectSS(const L& a, const L& b){
return ( ccw(a[0],a[1],b[0]) *ccw(a[0],a[1],b[1]) <= 0 ) &&
( ccw(b[0],b[1],a[0]) *ccw(b[0],b[1],a[1]) <= 0 );
}
bool isParallel(const P &a, const P &b){
return abs(cross(a,b)) < EPS;
}
bool isParallel(const L &a, const L &b){
return isParallel(a[1]-a[0], b[1]-b[0]);
}
P crosspointLL(const L &l, const L &m) {
double A = cross(l[1]-l[0], m[1]-m[0]);
double B = cross(l[1]-l[0], l[1]-m[0]);
return m[0] + B/A *(m[1]-m[0]);
}
double getangle(P a, P b){
return abs(arg(a/b));
}
pair<vector<vector<int> >, VP> arrangement(const vector<L> &l){
vector<VP> cp(l.size());
VP plist;
for(int i=0; i<(int)l.size(); i++){
for(int j=i+1; j<(int)l.size(); j++){
if(!isParallel(l[i], l[j]) && intersectSS(l[i], l[j])){
P cpij = crosspointLL(l[i], l[j]);
cp[i].push_back(cpij);
cp[j].push_back(cpij);
plist.push_back(cpij);
}
}
cp[i].push_back(l[i][0]);
cp[i].push_back(l[i][1]);
plist.push_back(l[i][0]);
plist.push_back(l[i][1]);
sort(cp[i].begin(), cp[i].end());
cp[i].erase(unique(cp[i].begin(), cp[i].end()), cp[i].end());
}
sort(plist.begin(), plist.end());
plist.erase(unique(plist.begin(), plist.end()), plist.end());
int n = plist.size();
map<P, int> conv;
for(int i=0; i<n; i++){
conv[plist[i]] = i;
}
vector<vector<int> > adj(n);
for(int i=0; i<(int)cp.size(); i++){
for(int j=0; j<(int)cp[i].size()-1; j++){
int jidx = conv[cp[i][j]];
int jp1idx = conv[cp[i][j+1]];
adj[jidx].push_back(jp1idx);
adj[jp1idx].push_back(jidx);
}
}
for(int i=0; i<n; i++){
sort(adj[i].begin(), adj[i].end());
adj[i].erase(unique(adj[i].begin(), adj[i].end()), adj[i].end());
}
return make_pair(adj, plist);
}
struct info{
double d;
int cidx, pidx;
info(int p, int c, double d):d(d),cidx(c),pidx(p){}
info(){}
bool operator < (const info &a) const{
return d > a.d;
}
};
int main(){
while(1){
int n;
cin >> n;
if(n == 0) break;
vector<L> l(n);
for(int i=0; i<n; i++){
for(int j=0; j<2; j++){
double x,y;
cin >> x >> y;
l[i][j] = P(x,y);
}
}
double sx,sy,gx,gy;
cin >> sx >> sy >> gx >> gy;
P s(sx,sy), g(gx,gy);
pair<vector<vector<int> >, VP> ret = arrangement(l);
vector<vector<int> > &adj = ret.first;
VP plist = ret.second;
int sidx=-1, gidx=-1;
for(int i=0; i<(int)plist.size(); i++){
if(plist[i] == s) sidx = i;
if(plist[i] == g) gidx = i;
}
priority_queue<info> wait;
wait.push(info(-1, sidx, 0));
vector<vector<double> > mincost(plist.size(), vector<double>(plist.size(), INF));
double ans = INF;
while(!wait.empty()){
int prev = wait.top().pidx;
int curr = wait.top().cidx;
double cost = wait.top().d;
wait.pop();
if(prev != -1 && cost > mincost[prev][curr] +EPS) continue;
if(curr == gidx){
ans = cost;
break;
}
for(int next: adj[curr]){
double ncost = (prev==-1)? 0: getangle(plist[next] -plist[curr], plist[curr] -plist[prev]);
if(cost +ncost +EPS < mincost[curr][next]){
mincost[curr][next] = cost +ncost;
wait.push(info(curr, next, cost +ncost));
}
}
}
if(ans == INF){
cout << -1 << endl;
}else{
cout << fixed << setprecision(10);
cout << ans*180/PI << endl;
}
}
return 0;
}
| ### Prompt
Construct a cpp code solution to the problem outlined:
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire.
The good news is that this robot doesn't consume energy to move on the wire, regardless of its distance. However, in order to change the direction at the end point of the wire or the intersection of the wires, it is necessary to rotate around that point, and energy is consumed by the rotation angle.
I want to move this robot from the start point to the goal point. For example, in the figure below, place the robot at start in the east direction (the positive direction of the x-axis in the figure below) and move it to the goal. There is a route from start to the goal via intersection A and intersection B, and a route via intersection A and intersection C, but the former has a longer travel distance but a smaller rotation angle, so it consumes less energy.
<image>
Your job is to create a program that reads the position of the wires on the floor, the start point, the goal point, and reports the minimum total rotation angle required to move from the start point to the goal point.
The robot may be placed in any direction at the start point and in any direction at the goal point.
Input
The input consists of multiple datasets. The format of each dataset is as follows:
n
x11 y11 x21 y21
x12 y12 x22 y22
..
..
..
x1n y1n x2n y2n
sx sy gx gy
n is an integer indicating the number of wires. x1i y1i shows the coordinates of one end point of the i-th wire, and x2i y2i shows the coordinates of the other end point of the i-th wire.
sx sy and gx gy indicate the coordinates of the start point and the goal point, respectively.
All given coordinates are integer values, and the x-axis and y-axis values are -1000 or more and 1000 or less. It may also be assumed that the start and finish points are on the end points of the given wire.
You can assume that n ≤ 50.
When n is 0, it indicates the end of input.
Output
For each dataset, output the minimum value of the total rotation angle on one line. If the robot cannot reach the goal point, output "-1". The output may contain an error of 0.00001 or less.
Example
Input
8
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 6 13 2
17 10 17 3
13 3 19 3
1 3 19 3
6
1 3 11 3
5 3 13 11
10 10 17 10
11 2 11 6
10 5 14 5
13 3 19 3
1 3 19 3
2
0 0 7 0
3 0 7 3
0 0 7 3
0
Output
270.0000
-1
36.86989765
### Response
```cpp
#include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
#include <map>
#include <queue>
using namespace std;
const double EPS = 1e-10;
const double INF = 1e12;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<double> P;
typedef vector<P> VP;
struct L : array<P, 2>{
L(const P& a, const P& b){ at(0)=a; at(1)=b; }
L(){}
};
namespace std{
bool operator < (const P& a, const P& b){
return !EQ(a.X,b.X) ? a.X<b.X : a.Y+EPS<b.Y;
}
bool operator == (const P& a, const P& b){
return abs(a-b) < EPS;
}
}
double dot(P a, P b){
return (conj(a)*b).X;
}
double cross(P a, P b){
return (conj(a)*b).Y;
}
int ccw(P a, P b, P c){
b -= a;
c -= a;
if(cross(b,c) > EPS) return +1; //ccw
if(cross(b,c) < -EPS) return -1; //cw
if(dot(b,c) < -EPS) return +2; //c-a-b
if(abs(c)-abs(b) > EPS) return -2; //a-b-c
return 0; //a-c-b
}
bool intersectSS(const L& a, const L& b){
return ( ccw(a[0],a[1],b[0]) *ccw(a[0],a[1],b[1]) <= 0 ) &&
( ccw(b[0],b[1],a[0]) *ccw(b[0],b[1],a[1]) <= 0 );
}
bool isParallel(const P &a, const P &b){
return abs(cross(a,b)) < EPS;
}
bool isParallel(const L &a, const L &b){
return isParallel(a[1]-a[0], b[1]-b[0]);
}
P crosspointLL(const L &l, const L &m) {
double A = cross(l[1]-l[0], m[1]-m[0]);
double B = cross(l[1]-l[0], l[1]-m[0]);
return m[0] + B/A *(m[1]-m[0]);
}
double getangle(P a, P b){
return abs(arg(a/b));
}
pair<vector<vector<int> >, VP> arrangement(const vector<L> &l){
vector<VP> cp(l.size());
VP plist;
for(int i=0; i<(int)l.size(); i++){
for(int j=i+1; j<(int)l.size(); j++){
if(!isParallel(l[i], l[j]) && intersectSS(l[i], l[j])){
P cpij = crosspointLL(l[i], l[j]);
cp[i].push_back(cpij);
cp[j].push_back(cpij);
plist.push_back(cpij);
}
}
cp[i].push_back(l[i][0]);
cp[i].push_back(l[i][1]);
plist.push_back(l[i][0]);
plist.push_back(l[i][1]);
sort(cp[i].begin(), cp[i].end());
cp[i].erase(unique(cp[i].begin(), cp[i].end()), cp[i].end());
}
sort(plist.begin(), plist.end());
plist.erase(unique(plist.begin(), plist.end()), plist.end());
int n = plist.size();
map<P, int> conv;
for(int i=0; i<n; i++){
conv[plist[i]] = i;
}
vector<vector<int> > adj(n);
for(int i=0; i<(int)cp.size(); i++){
for(int j=0; j<(int)cp[i].size()-1; j++){
int jidx = conv[cp[i][j]];
int jp1idx = conv[cp[i][j+1]];
adj[jidx].push_back(jp1idx);
adj[jp1idx].push_back(jidx);
}
}
for(int i=0; i<n; i++){
sort(adj[i].begin(), adj[i].end());
adj[i].erase(unique(adj[i].begin(), adj[i].end()), adj[i].end());
}
return make_pair(adj, plist);
}
struct info{
double d;
int cidx, pidx;
info(int p, int c, double d):d(d),cidx(c),pidx(p){}
info(){}
bool operator < (const info &a) const{
return d > a.d;
}
};
int main(){
while(1){
int n;
cin >> n;
if(n == 0) break;
vector<L> l(n);
for(int i=0; i<n; i++){
for(int j=0; j<2; j++){
double x,y;
cin >> x >> y;
l[i][j] = P(x,y);
}
}
double sx,sy,gx,gy;
cin >> sx >> sy >> gx >> gy;
P s(sx,sy), g(gx,gy);
pair<vector<vector<int> >, VP> ret = arrangement(l);
vector<vector<int> > &adj = ret.first;
VP plist = ret.second;
int sidx=-1, gidx=-1;
for(int i=0; i<(int)plist.size(); i++){
if(plist[i] == s) sidx = i;
if(plist[i] == g) gidx = i;
}
priority_queue<info> wait;
wait.push(info(-1, sidx, 0));
vector<vector<double> > mincost(plist.size(), vector<double>(plist.size(), INF));
double ans = INF;
while(!wait.empty()){
int prev = wait.top().pidx;
int curr = wait.top().cidx;
double cost = wait.top().d;
wait.pop();
if(prev != -1 && cost > mincost[prev][curr] +EPS) continue;
if(curr == gidx){
ans = cost;
break;
}
for(int next: adj[curr]){
double ncost = (prev==-1)? 0: getangle(plist[next] -plist[curr], plist[curr] -plist[prev]);
if(cost +ncost +EPS < mincost[curr][next]){
mincost[curr][next] = cost +ncost;
wait.push(info(curr, next, cost +ncost));
}
}
}
if(ans == INF){
cout << -1 << endl;
}else{
cout << fixed << setprecision(10);
cout << ans*180/PI << endl;
}
}
return 0;
}
``` |
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <utility>
#include <functional>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v;}
template<class T> inline string toStr(T x) { ostringstream sout; sout << x; return sout.str();}
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define REP(i,n) FOR(i,0,(n)-1)
const double EPS = 1e-12;
const double PI = acos(-1.0);
const int INF = INT_MAX/10;
int main() {
int n, m, c, s, g;
while(cin >> n >> m >> c >> s >> g, n) {
vector<vvi> rail(c, vvi(n, vi(n, INF)));
int x, y, d, e;
REP(i, m) {
cin >> x >> y >> d >> e;
rail[e-1][x-1][y-1] = min(d, rail[e-1][x-1][y-1]);
rail[e-1][y-1][x-1] = min(d, rail[e-1][y-1][x-1]);
}
REP(l, c) {
REP(k, n) {
REP(i, n) {
REP(j, n) {
rail[l][i][j] = min(rail[l][i][j], rail[l][i][k]+rail[l][k][j]);
}
}
}
}
vi p(c);
REP(i, c) {
cin >> p[i];
}
vvi q(c, vi());
vvi r(c, vi());
int tmp;
REP(i, c) {
REP(j, p[i]-1) {
cin >> tmp;
q[i].push_back(tmp);
}
REP(j, p[i]) {
cin >> tmp;
r[i].push_back(tmp);
}
q[i].push_back(20000);
}
vvi fee(c, vi(20000+1));
REP(l, c) {
int pos = 0;
FOR(i, 1, 20000) {
fee[l][i] = fee[l][i-1] + r[l][pos];
if(q[l][pos] == i) {
pos++;
}
}
}
REP(l, c) {
REP(i, n) {
REP(j, n) {
if(rail[l][i][j] != INF) {
rail[l][i][j] = fee[l][rail[l][i][j]];
}
}
}
}
vvi cost(n, vi(n, INF));
REP(l, c) {
REP(i, n) {
REP(j, n) {
cost[i][j] = min(cost[i][j], rail[l][i][j]);
}
}
}
REP(k, n) {
REP(i, n) {
REP(j, n) {
cost[i][j] = min(cost[i][j], cost[i][k]+cost[k][j]);
}
}
}
cout << (cost[s-1][g-1] == INF ? -1 : cost[s-1][g-1]) << endl;
}
return 0;
} | ### Prompt
Your task is to create a cpp solution to the following problem:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <utility>
#include <functional>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v;}
template<class T> inline string toStr(T x) { ostringstream sout; sout << x; return sout.str();}
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define REP(i,n) FOR(i,0,(n)-1)
const double EPS = 1e-12;
const double PI = acos(-1.0);
const int INF = INT_MAX/10;
int main() {
int n, m, c, s, g;
while(cin >> n >> m >> c >> s >> g, n) {
vector<vvi> rail(c, vvi(n, vi(n, INF)));
int x, y, d, e;
REP(i, m) {
cin >> x >> y >> d >> e;
rail[e-1][x-1][y-1] = min(d, rail[e-1][x-1][y-1]);
rail[e-1][y-1][x-1] = min(d, rail[e-1][y-1][x-1]);
}
REP(l, c) {
REP(k, n) {
REP(i, n) {
REP(j, n) {
rail[l][i][j] = min(rail[l][i][j], rail[l][i][k]+rail[l][k][j]);
}
}
}
}
vi p(c);
REP(i, c) {
cin >> p[i];
}
vvi q(c, vi());
vvi r(c, vi());
int tmp;
REP(i, c) {
REP(j, p[i]-1) {
cin >> tmp;
q[i].push_back(tmp);
}
REP(j, p[i]) {
cin >> tmp;
r[i].push_back(tmp);
}
q[i].push_back(20000);
}
vvi fee(c, vi(20000+1));
REP(l, c) {
int pos = 0;
FOR(i, 1, 20000) {
fee[l][i] = fee[l][i-1] + r[l][pos];
if(q[l][pos] == i) {
pos++;
}
}
}
REP(l, c) {
REP(i, n) {
REP(j, n) {
if(rail[l][i][j] != INF) {
rail[l][i][j] = fee[l][rail[l][i][j]];
}
}
}
}
vvi cost(n, vi(n, INF));
REP(l, c) {
REP(i, n) {
REP(j, n) {
cost[i][j] = min(cost[i][j], rail[l][i][j]);
}
}
}
REP(k, n) {
REP(i, n) {
REP(j, n) {
cost[i][j] = min(cost[i][j], cost[i][k]+cost[k][j]);
}
}
}
cout << (cost[s-1][g-1] == INF ? -1 : cost[s-1][g-1]) << endl;
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
template<class T> inline T sqr(T x) {return x*x;}
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define mp make_pair
#define each(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define exist(s,e) ((s).find(e)!=(s).end())
#define range(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n) range(i,0,n)
#define clr(a,b) memset((a), (b) ,sizeof(a))
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
const double eps = 1e-10;
const double pi = acos(-1.0);
const ll INF =1LL << 62;
const int inf =1 << 29;
int main(void){
for(int n, m, c, s, g; cin >> n >> m >> c >> s >> g, n;){
s--, g--;
vector<vvi> minDist_only(c, vvi(n, vi(n, inf)));
rep(cc, c) rep(i, n) minDist_only[cc][i][i] = 0;
rep(i, m){
int x, y, d, cc; cin >> x >> y >> d >> cc;
x--, y--; cc--;
minDist_only[cc][x][y] = min(minDist_only[cc][x][y], d);
minDist_only[cc][y][x] = min(minDist_only[cc][y][x], d);
}
vi p(c);
rep(i, c) cin >> p[i];
vvi q(c), r(c);
rep(i, c){
q[i] = vi(p[i] - 1);
r[i] = vi(p[i]);
for(auto && qq : q[i]) cin >> qq;
for(auto && rr : r[i]) cin >> rr;
}
vvi cost(c, vi(20001));
rep(cc, c){
int idx = 0;
range(d, 1, cost[cc].size()){
if(idx != p[cc] - 1 && d > q[cc][idx]) idx++;
cost[cc][d] = cost[cc][d - 1] + r[cc][idx];
}
}
rep(cc, c){
rep(k, n) rep(i, n) rep(j, n)
minDist_only[cc][i][j] = min(minDist_only[cc][i][j], minDist_only[cc][i][k] + minDist_only[cc][k][j]);
rep(i, n){
rep(j, n){
if(minDist_only[cc][i][j] >= inf) continue;
assert(minDist_only[cc][i][j] >= 0 && minDist_only[cc][i][j] < 20001);
minDist_only[cc][i][j] = cost[cc][minDist_only[cc][i][j]];
}
}
}
vvi minDist(n, vi(n, inf));
rep(cc, c) rep(i, n) rep(j, n) minDist[i][j] = min(minDist[i][j], minDist_only[cc][i][j]);
rep(k, n) rep(i, n) rep(j, n) minDist[i][j] = min(minDist[i][j], minDist[i][k] + minDist[k][j]);
if(minDist[s][g] == inf) cout << -1 << endl;
else cout << minDist[s][g] << endl;
}
return 0;
} | ### Prompt
Your challenge is to write a Cpp solution to the following problem:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
template<class T> inline T sqr(T x) {return x*x;}
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define pb push_back
#define mp make_pair
#define each(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define exist(s,e) ((s).find(e)!=(s).end())
#define range(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n) range(i,0,n)
#define clr(a,b) memset((a), (b) ,sizeof(a))
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
const double eps = 1e-10;
const double pi = acos(-1.0);
const ll INF =1LL << 62;
const int inf =1 << 29;
int main(void){
for(int n, m, c, s, g; cin >> n >> m >> c >> s >> g, n;){
s--, g--;
vector<vvi> minDist_only(c, vvi(n, vi(n, inf)));
rep(cc, c) rep(i, n) minDist_only[cc][i][i] = 0;
rep(i, m){
int x, y, d, cc; cin >> x >> y >> d >> cc;
x--, y--; cc--;
minDist_only[cc][x][y] = min(minDist_only[cc][x][y], d);
minDist_only[cc][y][x] = min(minDist_only[cc][y][x], d);
}
vi p(c);
rep(i, c) cin >> p[i];
vvi q(c), r(c);
rep(i, c){
q[i] = vi(p[i] - 1);
r[i] = vi(p[i]);
for(auto && qq : q[i]) cin >> qq;
for(auto && rr : r[i]) cin >> rr;
}
vvi cost(c, vi(20001));
rep(cc, c){
int idx = 0;
range(d, 1, cost[cc].size()){
if(idx != p[cc] - 1 && d > q[cc][idx]) idx++;
cost[cc][d] = cost[cc][d - 1] + r[cc][idx];
}
}
rep(cc, c){
rep(k, n) rep(i, n) rep(j, n)
minDist_only[cc][i][j] = min(minDist_only[cc][i][j], minDist_only[cc][i][k] + minDist_only[cc][k][j]);
rep(i, n){
rep(j, n){
if(minDist_only[cc][i][j] >= inf) continue;
assert(minDist_only[cc][i][j] >= 0 && minDist_only[cc][i][j] < 20001);
minDist_only[cc][i][j] = cost[cc][minDist_only[cc][i][j]];
}
}
}
vvi minDist(n, vi(n, inf));
rep(cc, c) rep(i, n) rep(j, n) minDist[i][j] = min(minDist[i][j], minDist_only[cc][i][j]);
rep(k, n) rep(i, n) rep(j, n) minDist[i][j] = min(minDist[i][j], minDist[i][k] + minDist[k][j]);
if(minDist[s][g] == inf) cout << -1 << endl;
else cout << minDist[s][g] << endl;
}
return 0;
}
``` |
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-9;
static const double PI = acos(-1.0);
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, s, n) for (int i = (s); i < (int)(n); i++)
#define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++)
#define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++)
#define MEMSET(v, h) memset((v), h, sizeof(v))
int n, m, c, s, g;
int matrix[30][110][110];
int ps[100];
int qs[100][100];
int rs[100][100];
int cost[30][20100];
int main() {
while (scanf("%d %d %d %d %d", &n, &m, &c, &s, &g), n) {
s--; g--;
MEMSET(matrix, 0x0f);
REP(a, c) REP(i, n) { matrix[a][i][i] = 0; }
REP(i, m) {
int f, t, d, g;
scanf("%d %d %d %d", &f, &t, &d, &g);
f--; t--; g--;
matrix[g][f][t] = matrix[g][t][f] = min(matrix[g][f][t], d);
}
REP(a, c) REP(k, n) REP(i, n) REP(j, n) {
matrix[a][i][j] = min(matrix[a][i][j], matrix[a][i][k] + matrix[a][k][j]);
}
REP(i, c) { scanf("%d", &ps[i]); }
REP(i, c) {
REP(j, ps[i] - 1) {
scanf("%d", &qs[i][j]);
}
qs[i][ps[i] - 1] = 1e+9;
REP(j, ps[i]) {
scanf("%d", &rs[i][j]);
}
cost[i][0] = 0;
int index = 0;
FOREQ(j, 1, 20010) {
while (qs[i][index] < j) { index++; }
cost[i][j] = cost[i][j - 1] + rs[i][index];
}
}
REP(a, c) REP(i, n) REP(j, n) {
if (matrix[a][i][j] == 0x0f0f0f0f) { continue; }
matrix[a][i][j] = cost[a][matrix[a][i][j]];
}
REP(a, c) REP(i, n) REP(j, n) {
matrix[0][i][j] = min(matrix[0][i][j], matrix[a][i][j]);
}
REP(k, n) REP(i, n) REP(j, n) {
matrix[0][i][j] = min(matrix[0][i][j], matrix[0][i][k] + matrix[0][k][j]);
}
if (matrix[0][s][g] == 0x0f0f0f0f) {
puts("-1");
} else {
printf("%d\n", matrix[0][s][g]);
}
}
} | ### Prompt
Create a solution in CPP for the following problem:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double EPS = 1e-9;
static const double PI = acos(-1.0);
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, s, n) for (int i = (s); i < (int)(n); i++)
#define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++)
#define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++)
#define MEMSET(v, h) memset((v), h, sizeof(v))
int n, m, c, s, g;
int matrix[30][110][110];
int ps[100];
int qs[100][100];
int rs[100][100];
int cost[30][20100];
int main() {
while (scanf("%d %d %d %d %d", &n, &m, &c, &s, &g), n) {
s--; g--;
MEMSET(matrix, 0x0f);
REP(a, c) REP(i, n) { matrix[a][i][i] = 0; }
REP(i, m) {
int f, t, d, g;
scanf("%d %d %d %d", &f, &t, &d, &g);
f--; t--; g--;
matrix[g][f][t] = matrix[g][t][f] = min(matrix[g][f][t], d);
}
REP(a, c) REP(k, n) REP(i, n) REP(j, n) {
matrix[a][i][j] = min(matrix[a][i][j], matrix[a][i][k] + matrix[a][k][j]);
}
REP(i, c) { scanf("%d", &ps[i]); }
REP(i, c) {
REP(j, ps[i] - 1) {
scanf("%d", &qs[i][j]);
}
qs[i][ps[i] - 1] = 1e+9;
REP(j, ps[i]) {
scanf("%d", &rs[i][j]);
}
cost[i][0] = 0;
int index = 0;
FOREQ(j, 1, 20010) {
while (qs[i][index] < j) { index++; }
cost[i][j] = cost[i][j - 1] + rs[i][index];
}
}
REP(a, c) REP(i, n) REP(j, n) {
if (matrix[a][i][j] == 0x0f0f0f0f) { continue; }
matrix[a][i][j] = cost[a][matrix[a][i][j]];
}
REP(a, c) REP(i, n) REP(j, n) {
matrix[0][i][j] = min(matrix[0][i][j], matrix[a][i][j]);
}
REP(k, n) REP(i, n) REP(j, n) {
matrix[0][i][j] = min(matrix[0][i][j], matrix[0][i][k] + matrix[0][k][j]);
}
if (matrix[0][s][g] == 0x0f0f0f0f) {
puts("-1");
} else {
printf("%d\n", matrix[0][s][g]);
}
}
}
``` |
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
class Edge
{
public:
int src,dst,cst;
Edge(int src, int dst, int cst)
:src(src),dst(dst),cst(cst)
{}
};
class State
{
public:
int p,c,d;
State(int p, int c, int d)
:p(p),c(c),d(d)
{}
bool operator<(const State& s) const {
if(c != s.c) return c > s.c;
return d > s.d;
}
};
typedef vector<vector<Edge> > Graph;
int N,M,C,S,G;
int COST[10001][20];
int P[20], Q[20][51], R[20][51];
int ct[100][100][20];
int dijkstra(int Start, int Goal, int com, Graph& graph)
{
priority_queue<State> q;
q.push(State(Start, 0, 0));
bool vis[100] = {0};
while(!q.empty()) {
State s=q.top(); q.pop();
if(vis[s.p]) continue;
vis[s.p] = 1;
if(s.p == Goal) return s.c;
for(int i=0; i<graph[s.p].size(); i++) {
Edge& e = graph[s.p][i];
int td = s.d + e.cst;
int nc = 0;
if(td > Q[com][P[com] - 1]) {
nc = COST[Q[com][P[com] - 1]][com] + abs(td - Q[com][P[com]-1]) * R[com][P[com]-1];
}
else nc = COST[td][com];
if(vis[e.dst]) continue;
q.push(State(e.dst, nc, td));
}
}
return -1;
}
int solve(int Start, int Goal, Graph& graph)
{
priority_queue<State> q;
q.push(State(Start, 0, 0));
bool vis[100] = {0};
while(!q.empty()) {
State s=q.top(); q.pop();
if(vis[s.p]) continue;
vis[s.p] = 1;
if(s.p == Goal) return s.c;
for(int i=0; i<graph[s.p].size(); i++) {
Edge& e = graph[s.p][i];
if(vis[e.dst]) continue;
q.push(State(e.dst, s.c + e.cst, 0));
}
}
return -1;
}
int main()
{
while(cin >> N >> M >> C >> S >> G, (N||M||C||S||G)) {
S--; G--;
vector<Graph> graph(C);
for(int i=0; i<C; i++)
graph[i].resize(N);
for(int i=0; i<M; i++) {
int a,b,c,d;
cin >> a >> b >> d >> c;
a--; b--; c--;
graph[c][a].push_back(Edge(a,b,d));
graph[c][b].push_back(Edge(b,a,d));
}
for(int i=0; i<C; i++)
cin >> P[i];
for(int i=0; i<C; i++) {
Q[i][0] = 0;
for(int j=1; j<P[i]; j++)
cin >> Q[i][j];
for(int j=0; j<P[i]; j++)
cin >> R[i][j];
}
for(int i=0; i<C; i++)
COST[0][i] = 0;
for(int i=0; i<C; i++)
for(int j=1; j<P[i]; j++)
for(int k=Q[i][j-1]+1; k<=Q[i][j]; k++)
COST[k][i] = COST[k-1][i] + R[i][j - 1];
for(int k=0; k<C; k++)
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++) {
ct[i][j][k] = ct[j][i][k] = dijkstra(i, j, k, graph[k]);
}
Graph final(N);
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++) {
int mmm = (1<<28);
for(int k=0; k<C; k++) {
if(ct[i][j][k] == -1) continue;
mmm = min(mmm, ct[i][j][k]);
}
if(mmm == (1<<28)) continue;
final[i].push_back(Edge(i,j,mmm));
final[j].push_back(Edge(j,i,mmm));
}
cout << solve(S, G, final) << endl;
}
} | ### Prompt
Please provide a cpp coded solution to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
class Edge
{
public:
int src,dst,cst;
Edge(int src, int dst, int cst)
:src(src),dst(dst),cst(cst)
{}
};
class State
{
public:
int p,c,d;
State(int p, int c, int d)
:p(p),c(c),d(d)
{}
bool operator<(const State& s) const {
if(c != s.c) return c > s.c;
return d > s.d;
}
};
typedef vector<vector<Edge> > Graph;
int N,M,C,S,G;
int COST[10001][20];
int P[20], Q[20][51], R[20][51];
int ct[100][100][20];
int dijkstra(int Start, int Goal, int com, Graph& graph)
{
priority_queue<State> q;
q.push(State(Start, 0, 0));
bool vis[100] = {0};
while(!q.empty()) {
State s=q.top(); q.pop();
if(vis[s.p]) continue;
vis[s.p] = 1;
if(s.p == Goal) return s.c;
for(int i=0; i<graph[s.p].size(); i++) {
Edge& e = graph[s.p][i];
int td = s.d + e.cst;
int nc = 0;
if(td > Q[com][P[com] - 1]) {
nc = COST[Q[com][P[com] - 1]][com] + abs(td - Q[com][P[com]-1]) * R[com][P[com]-1];
}
else nc = COST[td][com];
if(vis[e.dst]) continue;
q.push(State(e.dst, nc, td));
}
}
return -1;
}
int solve(int Start, int Goal, Graph& graph)
{
priority_queue<State> q;
q.push(State(Start, 0, 0));
bool vis[100] = {0};
while(!q.empty()) {
State s=q.top(); q.pop();
if(vis[s.p]) continue;
vis[s.p] = 1;
if(s.p == Goal) return s.c;
for(int i=0; i<graph[s.p].size(); i++) {
Edge& e = graph[s.p][i];
if(vis[e.dst]) continue;
q.push(State(e.dst, s.c + e.cst, 0));
}
}
return -1;
}
int main()
{
while(cin >> N >> M >> C >> S >> G, (N||M||C||S||G)) {
S--; G--;
vector<Graph> graph(C);
for(int i=0; i<C; i++)
graph[i].resize(N);
for(int i=0; i<M; i++) {
int a,b,c,d;
cin >> a >> b >> d >> c;
a--; b--; c--;
graph[c][a].push_back(Edge(a,b,d));
graph[c][b].push_back(Edge(b,a,d));
}
for(int i=0; i<C; i++)
cin >> P[i];
for(int i=0; i<C; i++) {
Q[i][0] = 0;
for(int j=1; j<P[i]; j++)
cin >> Q[i][j];
for(int j=0; j<P[i]; j++)
cin >> R[i][j];
}
for(int i=0; i<C; i++)
COST[0][i] = 0;
for(int i=0; i<C; i++)
for(int j=1; j<P[i]; j++)
for(int k=Q[i][j-1]+1; k<=Q[i][j]; k++)
COST[k][i] = COST[k-1][i] + R[i][j - 1];
for(int k=0; k<C; k++)
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++) {
ct[i][j][k] = ct[j][i][k] = dijkstra(i, j, k, graph[k]);
}
Graph final(N);
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++) {
int mmm = (1<<28);
for(int k=0; k<C; k++) {
if(ct[i][j][k] == -1) continue;
mmm = min(mmm, ct[i][j][k]);
}
if(mmm == (1<<28)) continue;
final[i].push_back(Edge(i,j,mmm));
final[j].push_back(Edge(j,i,mmm));
}
cout << solve(S, G, final) << endl;
}
}
``` |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <cstring>
#include <cmath>
#include <queue>
#include <map>
#include <set>
using namespace std;
#define rep(i,n) for(int i=0; i<n; i++)
#define FOR(i,s,n) for(int i=s; i<n; i++)
#define ALL(x) x.begin(), x.end()
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef vector<int> vi;
int dist[101][101][21];
int cost[101][101];
const int INF = 1e7;
int main() {
int _n, _m, _c, _s, _g;
while(cin >> _n >> _m >> _c >> _s >> _g, _n) {
rep(i,101) rep(j,101) rep(k,21) dist[i][j][k] = INF;
rep(i,101) rep(j,101) cost[i][j] = INF;
rep(i, _m) {
int x, y, d, c;
cin >> x >> y >> d >> c;
dist[x][y][c] = min(dist[x][y][c], d);
dist[y][x][c] = min(dist[y][x][c], d);
}
vector<int> p(_c);
vector< vector<int> > q(_c), r(_c);
rep(i,_c) cin >> p[i];
rep(i,_c) {
q[i].resize(p[i]+1);
q[i][0] = 0;
for(int j=1; j<p[i]; j++) {
cin >> q[i][j];
}
q[i][p[i]] = INF;
r[i].resize(p[i]+1);
rep(j, p[i]) {
cin >> r[i][j];
}
}
rep(c,_c) rep(k,_n) rep(i,_n) rep(j,_n)
dist[i+1][j+1][c+1] = min( dist[i+1][j+1][c+1], dist[i+1][k+1][c+1] + dist[k+1][j+1][c+1] );
rep(c,_c) rep(i,_n) rep(j,_n) {
int co = 0;
int d = 0, pos = 0;
while(d+q[c][pos+1] < dist[i+1][j+1][c+1]) {
co += r[c][pos] * (q[c][pos+1]-q[c][pos]);
pos++;
}
co += r[c][pos] * (dist[i+1][j+1][c+1]-q[c][pos]);
cost[i+1][j+1] = min(cost[i+1][j+1], co);
}
rep(k,_n) rep(i,_n) rep(j,_n)
cost[i+1][j+1] = min( cost[i+1][j+1], cost[i+1][k+1] + cost[k+1][j+1] );
if( cost[_s][_g] >= INF ) {
cout << -1 << endl;
} else {
cout << cost[_s][_g] << endl;
}
}
return 0;
} | ### Prompt
Develop a solution in cpp to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <cstring>
#include <cmath>
#include <queue>
#include <map>
#include <set>
using namespace std;
#define rep(i,n) for(int i=0; i<n; i++)
#define FOR(i,s,n) for(int i=s; i<n; i++)
#define ALL(x) x.begin(), x.end()
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef vector<int> vi;
int dist[101][101][21];
int cost[101][101];
const int INF = 1e7;
int main() {
int _n, _m, _c, _s, _g;
while(cin >> _n >> _m >> _c >> _s >> _g, _n) {
rep(i,101) rep(j,101) rep(k,21) dist[i][j][k] = INF;
rep(i,101) rep(j,101) cost[i][j] = INF;
rep(i, _m) {
int x, y, d, c;
cin >> x >> y >> d >> c;
dist[x][y][c] = min(dist[x][y][c], d);
dist[y][x][c] = min(dist[y][x][c], d);
}
vector<int> p(_c);
vector< vector<int> > q(_c), r(_c);
rep(i,_c) cin >> p[i];
rep(i,_c) {
q[i].resize(p[i]+1);
q[i][0] = 0;
for(int j=1; j<p[i]; j++) {
cin >> q[i][j];
}
q[i][p[i]] = INF;
r[i].resize(p[i]+1);
rep(j, p[i]) {
cin >> r[i][j];
}
}
rep(c,_c) rep(k,_n) rep(i,_n) rep(j,_n)
dist[i+1][j+1][c+1] = min( dist[i+1][j+1][c+1], dist[i+1][k+1][c+1] + dist[k+1][j+1][c+1] );
rep(c,_c) rep(i,_n) rep(j,_n) {
int co = 0;
int d = 0, pos = 0;
while(d+q[c][pos+1] < dist[i+1][j+1][c+1]) {
co += r[c][pos] * (q[c][pos+1]-q[c][pos]);
pos++;
}
co += r[c][pos] * (dist[i+1][j+1][c+1]-q[c][pos]);
cost[i+1][j+1] = min(cost[i+1][j+1], co);
}
rep(k,_n) rep(i,_n) rep(j,_n)
cost[i+1][j+1] = min( cost[i+1][j+1], cost[i+1][k+1] + cost[k+1][j+1] );
if( cost[_s][_g] >= INF ) {
cout << -1 << endl;
} else {
cout << cost[_s][_g] << endl;
}
}
return 0;
}
``` |
#include <bits/stdc++.h>
using namespace std;
#define for_(i,a,b) for(int i=(a);i<(b);++i)
#define minit(a, b) memset(a, b, sizeof(a))
#define size_of(a) (int)(a).size()
typedef long long lint;
struct Edge {
int to; lint dst;
Edge (int to_, lint dst_) : to(to_), dst(dst_) {}
bool operator > (const Edge& e) const { return dst > e.dst; }
};
void minUpdate(lint& a, lint b) { a = min(a, b); }
const int iINF = 1L << 30;
const lint lINF = 1LL << 60;
int n, m, c, s, g;
int p[22], q[22][55], r[22][55];
vector< vector< Edge > > edges;
lint cost[22][111][111], dist[22][111][111], price[22][20010];
lint minCost[111];
int djk() {
fill(minCost, minCost + 111, lINF);
priority_queue< Edge, vector< Edge >, greater< Edge > > que;
que.push(Edge(s, 0));
minCost[s] = 0;
while (!que.empty()) {
Edge e = que.top(); que.pop();
int u = e.to, dst = e.dst;
if (minCost[u] < dst) continue;
for_(ci,0,c) {
for_(v,0,n) {
if (cost[ci][u][v] == iINF) continue;
int nx_cost = dst + cost[ci][u][v];
if (minCost[v] > nx_cost) {
minCost[v] = nx_cost;
que.push(Edge(v, nx_cost));
}
}
}
}
return (minCost[g] == lINF) ? -1 : minCost[g];
}
void solve() {
for_(ci,0,c) {
for_(k,0,n) for_(i,0,n) for_(j,0,n) {
minUpdate(dist[ci][i][j], dist[ci][i][k] + dist[ci][k][j]);
}
}
for_(ci, 0, c) {
for_(u,0,n) for_(v,0,n) {
if (dist[ci][u][v] == iINF) {
cost[ci][u][v] = iINF;
continue;
}
assert(dist[ci][u][v] <= 20000);
cost[ci][u][v] = price[ci][dist[ci][u][v]];
}
}
cout << djk() << endl;
}
int main() {
while (cin >> n >> m >> c >> s >> g, n) {
--s; --g;
for_(i,0,22) for_(j,0,111) for_(k,0,111) dist[i][j][k] = iINF;
edges.assign(n, vector< Edge >());
for_(i,0,m) {
int x, y, cmp; lint dst;
cin >> x >> y >> dst >> cmp;
--x; --y; --cmp;
edges[x].push_back(Edge(y, dst));
edges[y].push_back(Edge(x, dst));
dist[cmp][x][y] = dist[cmp][y][x] = min(dist[cmp][y][x], dst);
}
for_(ci,0,c) cin >> p[ci];
minit(price, 0);
for_(ci,0,c) {
for_(j,0,p[ci]-1) cin >> q[ci][j];
for_(j,0,p[ci]) cin >> r[ci][j];
q[ci][p[ci]-1] = 20005;
int cur = 1;
for_(j,0,p[ci]) {
int qj = q[ci][j];
while (cur <= q[ci][j]) {
price[ci][cur] = price[ci][cur - 1] + r[ci][j];
++cur;
}
}
}
solve();
}
} | ### Prompt
Develop a solution in Cpp to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
#define for_(i,a,b) for(int i=(a);i<(b);++i)
#define minit(a, b) memset(a, b, sizeof(a))
#define size_of(a) (int)(a).size()
typedef long long lint;
struct Edge {
int to; lint dst;
Edge (int to_, lint dst_) : to(to_), dst(dst_) {}
bool operator > (const Edge& e) const { return dst > e.dst; }
};
void minUpdate(lint& a, lint b) { a = min(a, b); }
const int iINF = 1L << 30;
const lint lINF = 1LL << 60;
int n, m, c, s, g;
int p[22], q[22][55], r[22][55];
vector< vector< Edge > > edges;
lint cost[22][111][111], dist[22][111][111], price[22][20010];
lint minCost[111];
int djk() {
fill(minCost, minCost + 111, lINF);
priority_queue< Edge, vector< Edge >, greater< Edge > > que;
que.push(Edge(s, 0));
minCost[s] = 0;
while (!que.empty()) {
Edge e = que.top(); que.pop();
int u = e.to, dst = e.dst;
if (minCost[u] < dst) continue;
for_(ci,0,c) {
for_(v,0,n) {
if (cost[ci][u][v] == iINF) continue;
int nx_cost = dst + cost[ci][u][v];
if (minCost[v] > nx_cost) {
minCost[v] = nx_cost;
que.push(Edge(v, nx_cost));
}
}
}
}
return (minCost[g] == lINF) ? -1 : minCost[g];
}
void solve() {
for_(ci,0,c) {
for_(k,0,n) for_(i,0,n) for_(j,0,n) {
minUpdate(dist[ci][i][j], dist[ci][i][k] + dist[ci][k][j]);
}
}
for_(ci, 0, c) {
for_(u,0,n) for_(v,0,n) {
if (dist[ci][u][v] == iINF) {
cost[ci][u][v] = iINF;
continue;
}
assert(dist[ci][u][v] <= 20000);
cost[ci][u][v] = price[ci][dist[ci][u][v]];
}
}
cout << djk() << endl;
}
int main() {
while (cin >> n >> m >> c >> s >> g, n) {
--s; --g;
for_(i,0,22) for_(j,0,111) for_(k,0,111) dist[i][j][k] = iINF;
edges.assign(n, vector< Edge >());
for_(i,0,m) {
int x, y, cmp; lint dst;
cin >> x >> y >> dst >> cmp;
--x; --y; --cmp;
edges[x].push_back(Edge(y, dst));
edges[y].push_back(Edge(x, dst));
dist[cmp][x][y] = dist[cmp][y][x] = min(dist[cmp][y][x], dst);
}
for_(ci,0,c) cin >> p[ci];
minit(price, 0);
for_(ci,0,c) {
for_(j,0,p[ci]-1) cin >> q[ci][j];
for_(j,0,p[ci]) cin >> r[ci][j];
q[ci][p[ci]-1] = 20005;
int cur = 1;
for_(j,0,p[ci]) {
int qj = q[ci][j];
while (cur <= q[ci][j]) {
price[ci][cur] = price[ci][cur - 1] + r[ci][j];
++cur;
}
}
}
solve();
}
}
``` |
/*
Railway Connection(https://onlinejudge.u-aizu.ac.jp/problems/1182)
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cmath>
#include <complex>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <bitset>
#include <algorithm>
#include <numeric>
#include <functional>
#include <cassert>
#include <iomanip>
using namespace std;
#define Rep(b, e, i) for(int i = b; i <= e; i++)
#define Repr(e, b, i) for(int i = e; i >= b; i--)
#define rep(n, i) Rep(0, n-1, i)
#define repr(n, i) Repr(n-1, 0, i)
#define all(v) (v).begin(), (v).end()
#define pb(v) push_back(v)
#define uniq(v) (v).erase(unique(all(v)),(v).end())
#define bitcnt(x) __builtin_popcount(x)
#define fst first
#define snd second
#define Pqaz(T) priority_queue<T,vector<T>,greater<T>>
#define Pqza(T) priority_queue<T>
#define put(x) cout << x;
#define putsp(x) cout << x << ' ';
#define putln(x) cout << x << endl;
#define ENJYU std::ios::sync_with_stdio(false);std::cin.tie(0);
typedef long long ll;
typedef pair<ll, ll> llP;
typedef pair<int, int> intP;
typedef complex<double> comp;
typedef vector <int> vec;
typedef vector <ll> vecll;
typedef vector <double> vecd;
typedef vector <vec> mat;
typedef vector <vecll> matll;
typedef vector <vecd> matd;
//vector の中身を出力
template <class T>ostream &operator<<(ostream &o,const vector<T>&v)
{o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}
const int MAX = 200000;
const double PI = 3.14159265358979323846;
const double EPS = 1e-12;
const int INF = 1<<29;
const int MOD = 1000000007;
void solve(void){
int N, M, C, S, G;
while (cin >> N >> M >> C >> S >> G) {
if (!N) break;
S--, G--;
//dis[c][x][y] := cを使ってxからyに行く時の最短経路
vector <mat> dis(C, mat (N, vec (N, INF)));
rep(M, i)
{
int x, y, d, c;
cin >> x >> y >> d >> c;
x--, y--, c--;
dis[c][x][y] = dis[c][y][x] = min(dis[c][x][y], d);
}
rep(C, c)
{
//各Cの距離についてWF
rep(N, k) rep(N, i) rep(N, j)
{
dis[c][i][j] = min(dis[c][i][j], dis[c][i][k] + dis[c][k][j]);
}
}
vec ps(C);
rep(C, i) cin >> ps[i];
//cost[x][y] := xからyに行く時の最低コスト
mat cost(N, vec(N, INF));
rep(C, c)
{
vec qs(ps[c]+1, 0), rs(ps[c]);
//qs[0] = 0, qs[ps[i]] = INF
qs[ps[c]] = INF;
rep(ps[c]-1, j) cin >> qs[j+1];
rep(ps[c], j) cin >> rs[j];
rep(N, x) rep(N, y)
{
int d = dis[c][x][y];
if (d == INF)
{
continue;
}
int fare = 0;
rep(ps[c]+1, p)
{
if (d > qs[p])
{
fare += min(qs[p+1]-qs[p], d-qs[p]) * rs[p];
}
}
cost[x][y] = min(cost[x][y], fare);
}
}
//コストについてWF
rep(N, k) rep(N, i) rep(N, j)
{
cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j]);
}
if (cost[S][G] == INF)
{
cout << -1 << endl;
}
else
{
cout << cost[S][G] << endl;
}
}
}
int main(void){
solve();
//cout << "yui(*-v・)yui" << endl;
return 0;
}
| ### Prompt
Please provide a CPP coded solution to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
/*
Railway Connection(https://onlinejudge.u-aizu.ac.jp/problems/1182)
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cmath>
#include <complex>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <bitset>
#include <algorithm>
#include <numeric>
#include <functional>
#include <cassert>
#include <iomanip>
using namespace std;
#define Rep(b, e, i) for(int i = b; i <= e; i++)
#define Repr(e, b, i) for(int i = e; i >= b; i--)
#define rep(n, i) Rep(0, n-1, i)
#define repr(n, i) Repr(n-1, 0, i)
#define all(v) (v).begin(), (v).end()
#define pb(v) push_back(v)
#define uniq(v) (v).erase(unique(all(v)),(v).end())
#define bitcnt(x) __builtin_popcount(x)
#define fst first
#define snd second
#define Pqaz(T) priority_queue<T,vector<T>,greater<T>>
#define Pqza(T) priority_queue<T>
#define put(x) cout << x;
#define putsp(x) cout << x << ' ';
#define putln(x) cout << x << endl;
#define ENJYU std::ios::sync_with_stdio(false);std::cin.tie(0);
typedef long long ll;
typedef pair<ll, ll> llP;
typedef pair<int, int> intP;
typedef complex<double> comp;
typedef vector <int> vec;
typedef vector <ll> vecll;
typedef vector <double> vecd;
typedef vector <vec> mat;
typedef vector <vecll> matll;
typedef vector <vecd> matd;
//vector の中身を出力
template <class T>ostream &operator<<(ostream &o,const vector<T>&v)
{o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}
const int MAX = 200000;
const double PI = 3.14159265358979323846;
const double EPS = 1e-12;
const int INF = 1<<29;
const int MOD = 1000000007;
void solve(void){
int N, M, C, S, G;
while (cin >> N >> M >> C >> S >> G) {
if (!N) break;
S--, G--;
//dis[c][x][y] := cを使ってxからyに行く時の最短経路
vector <mat> dis(C, mat (N, vec (N, INF)));
rep(M, i)
{
int x, y, d, c;
cin >> x >> y >> d >> c;
x--, y--, c--;
dis[c][x][y] = dis[c][y][x] = min(dis[c][x][y], d);
}
rep(C, c)
{
//各Cの距離についてWF
rep(N, k) rep(N, i) rep(N, j)
{
dis[c][i][j] = min(dis[c][i][j], dis[c][i][k] + dis[c][k][j]);
}
}
vec ps(C);
rep(C, i) cin >> ps[i];
//cost[x][y] := xからyに行く時の最低コスト
mat cost(N, vec(N, INF));
rep(C, c)
{
vec qs(ps[c]+1, 0), rs(ps[c]);
//qs[0] = 0, qs[ps[i]] = INF
qs[ps[c]] = INF;
rep(ps[c]-1, j) cin >> qs[j+1];
rep(ps[c], j) cin >> rs[j];
rep(N, x) rep(N, y)
{
int d = dis[c][x][y];
if (d == INF)
{
continue;
}
int fare = 0;
rep(ps[c]+1, p)
{
if (d > qs[p])
{
fare += min(qs[p+1]-qs[p], d-qs[p]) * rs[p];
}
}
cost[x][y] = min(cost[x][y], fare);
}
}
//コストについてWF
rep(N, k) rep(N, i) rep(N, j)
{
cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j]);
}
if (cost[S][G] == INF)
{
cout << -1 << endl;
}
else
{
cout << cost[S][G] << endl;
}
}
}
int main(void){
solve();
//cout << "yui(*-v・)yui" << endl;
return 0;
}
``` |
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
const int INF=1000000000;
using namespace std;
struct edge{int to,cost;};
typedef pair<int,int>P;
int V,d[101];
vector<edge>G[101];
void dijkstra(int s){
priority_queue<P,vector<P>,greater<P> >que;
fill(d,d+V,INF);
d[s]=0;
que.push(P(0,s));
while(!que.empty()){
P p=que.top();
que.pop();
int v=p.second;
if(d[v]<p.first)continue;
for(int i=0;i<G[v].size();i++){
edge e=G[v][i];
if(d[e.to]>d[v]+e.cost){
d[e.to]=d[v]+e.cost;
que.push(P(d[e.to],e.to));
}
}
}
}
int main(void){
int n,m,c,s,g,x,y,D,C;
int p[21],q[21][51],r[21][51];
int graph[21][101][101],Cost[21][20001];
while(cin >> n >> m >> c >> s >> g,n|m|c|s|g){
for(int i=0;i<101;i++)G[i].clear();
for(int i=0;i<21;i++)
for(int j=0;j<101;j++)
for(int k=0;k<101;k++)
graph[i][j][k]=INF;
for(int i=0;i<21;i++)
for(int j=0;j<101;j++)
graph[i][j][j]=0;
for(int i=0;i<m;i++){
cin >> x >> y >> D >> C;
graph[C][x][y]=graph[C][y][x]=min(graph[C][x][y],D);
}
for(int i=1;i<=c;i++)cin >> p[i];
for(int i=1;i<=c;i++){
for(int j=1;j<p[i];j++)cin >> q[i][j];
for(int j=1;j<=p[i];j++)cin >> r[i][j];
}
for(int i=0;i<21;i++)
for(int j=0;j<20001;j++)
Cost[i][j]=0;
for(int i=1;i<=c;i++){
for(int j=1,k=1;j<20001;j++){
if(k<p[i] && q[i][k]<j)k++;
Cost[i][j]=Cost[i][j-1]+r[i][k];
}
}
for(int l=1;l<=c;l++){
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
graph[l][i][j]=min(graph[l][i][j],graph[l][i][k]+graph[l][k][j]);
}
}
}
}
for(int k=1;k<=c;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(graph[k][i][j]!=INF)
graph[0][i][j]=min(graph[0][i][j],Cost[k][graph[k][i][j]]);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(graph[0][i][j]==INF)continue;
edge e;
e.to=j;
e.cost=graph[0][i][j];
G[i].push_back(e);
}
}
V=n+1;
dijkstra(s);
if(d[g]==INF)cout << -1 << endl;
else cout << d[g] << endl;
}
return 0;
} | ### Prompt
In CPP, your task is to solve the following problem:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
const int INF=1000000000;
using namespace std;
struct edge{int to,cost;};
typedef pair<int,int>P;
int V,d[101];
vector<edge>G[101];
void dijkstra(int s){
priority_queue<P,vector<P>,greater<P> >que;
fill(d,d+V,INF);
d[s]=0;
que.push(P(0,s));
while(!que.empty()){
P p=que.top();
que.pop();
int v=p.second;
if(d[v]<p.first)continue;
for(int i=0;i<G[v].size();i++){
edge e=G[v][i];
if(d[e.to]>d[v]+e.cost){
d[e.to]=d[v]+e.cost;
que.push(P(d[e.to],e.to));
}
}
}
}
int main(void){
int n,m,c,s,g,x,y,D,C;
int p[21],q[21][51],r[21][51];
int graph[21][101][101],Cost[21][20001];
while(cin >> n >> m >> c >> s >> g,n|m|c|s|g){
for(int i=0;i<101;i++)G[i].clear();
for(int i=0;i<21;i++)
for(int j=0;j<101;j++)
for(int k=0;k<101;k++)
graph[i][j][k]=INF;
for(int i=0;i<21;i++)
for(int j=0;j<101;j++)
graph[i][j][j]=0;
for(int i=0;i<m;i++){
cin >> x >> y >> D >> C;
graph[C][x][y]=graph[C][y][x]=min(graph[C][x][y],D);
}
for(int i=1;i<=c;i++)cin >> p[i];
for(int i=1;i<=c;i++){
for(int j=1;j<p[i];j++)cin >> q[i][j];
for(int j=1;j<=p[i];j++)cin >> r[i][j];
}
for(int i=0;i<21;i++)
for(int j=0;j<20001;j++)
Cost[i][j]=0;
for(int i=1;i<=c;i++){
for(int j=1,k=1;j<20001;j++){
if(k<p[i] && q[i][k]<j)k++;
Cost[i][j]=Cost[i][j-1]+r[i][k];
}
}
for(int l=1;l<=c;l++){
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
graph[l][i][j]=min(graph[l][i][j],graph[l][i][k]+graph[l][k][j]);
}
}
}
}
for(int k=1;k<=c;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(graph[k][i][j]!=INF)
graph[0][i][j]=min(graph[0][i][j],Cost[k][graph[k][i][j]]);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(graph[0][i][j]==INF)continue;
edge e;
e.to=j;
e.cost=graph[0][i][j];
G[i].push_back(e);
}
}
V=n+1;
dijkstra(s);
if(d[g]==INF)cout << -1 << endl;
else cout << d[g] << endl;
}
return 0;
}
``` |
#include <bits/stdc++.h>
class Solve {
private:
using vi = std::vector<int64_t>;
using vvi = std::vector<vi>;
using vvvi = std::vector<vvi>;
using i3 = std::array<int64_t, 3>;
using vi3 = std::vector<i3>;
using vvi3 = std::vector<vi3>;
public:
bool is_last_query{};
Solve()
{
int n, m, company, start, goal;
scanf("%d%d%d%d%d", &n, &m, &company, &start, &goal);
if (n == 0)
{
is_last_query = true;
return;
}
start--;
goal--;
vvvi companyGraph(company, vvi(n, vi(n, 1ll << 60)));
for (int i{}; i < m; i++)
{
int x, y, d, c;
scanf("%d%d%d%d", &x, &y, &d, &c);
x--;
y--;
c--;
companyGraph[c][x][y] = std::min(companyGraph[c][x][y], (int64_t)d);
companyGraph[c][y][x] = std::min(companyGraph[c][y][x], (int64_t)d);
}
for (auto& e: companyGraph)
for (int i{}; i < n; i++)
e[i][i] = 0;
vvi graph(n, vi(n, 1ll << 60));
vi p(company);
for (auto& e: p) scanf("%d", &e);
for (int c_i{}; c_i < company; c_i++)
{
// {point, cost, cost_delta}
vi3 costs(p[c_i]);
for (int i{1}; i < p[c_i]; i++)
scanf("%d", &costs[i][0]);
for (int i{}; i < p[c_i]; i++)
scanf("%d", &costs[i][2]);
for (int i{1}; i < p[c_i]; i++)
costs[i][1] = costs[i - 1][1] + costs[i - 1][2] * (costs[i][0] - costs[i - 1][0]);
auto& eachGraph{companyGraph[c_i]};
for (int mid{}; mid < n; mid++)
for (int from{}; from < n; from++)
for (int to{}; to < n; to++)
eachGraph[from][to] = std::min(eachGraph[from][to], eachGraph[from][mid] + eachGraph[mid][to]);
for (int i{}; i < n; i++)
for (int j{}; j < n; j++)
{
int64_t dist{eachGraph[i][j]};
if (dist == (1ll << 60)) continue;
int64_t left{}, right{p[c_i]};
while (right - left > 1)
{
int64_t mid{(right + left) >> 1};
if (costs[mid][0] <= dist) left = mid;
else right = mid;
}
graph[i][j] = std::min(graph[i][j], costs[left][1] + costs[left][2] * (dist - costs[left][0]));
}
}
vi dist(n, 1ll << 60);
dist[start] = 0;
using pii = std::pair<int64_t, int>;
std::priority_queue<pii, std::vector<pii>, std::greater<pii>> dij;
dij.push({0, start});
while (!dij.empty())
{
auto now{dij.top()};
dij.pop();
if (now.first > dist[now.second]) continue;
for (int i{}; i < n; i++)
if (now.first + graph[now.second][i] < dist[i])
{
dist[i] = now.first + graph[now.second][i];
dij.push({dist[i], i});
}
}
if (dist[goal] == (1ll << 60)) puts("-1");
else printf("%lld\n", dist[goal]);
}
};
int main()
{
while (!Solve().is_last_query);
return 0;
}
| ### Prompt
In CPP, your task is to solve the following problem:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <bits/stdc++.h>
class Solve {
private:
using vi = std::vector<int64_t>;
using vvi = std::vector<vi>;
using vvvi = std::vector<vvi>;
using i3 = std::array<int64_t, 3>;
using vi3 = std::vector<i3>;
using vvi3 = std::vector<vi3>;
public:
bool is_last_query{};
Solve()
{
int n, m, company, start, goal;
scanf("%d%d%d%d%d", &n, &m, &company, &start, &goal);
if (n == 0)
{
is_last_query = true;
return;
}
start--;
goal--;
vvvi companyGraph(company, vvi(n, vi(n, 1ll << 60)));
for (int i{}; i < m; i++)
{
int x, y, d, c;
scanf("%d%d%d%d", &x, &y, &d, &c);
x--;
y--;
c--;
companyGraph[c][x][y] = std::min(companyGraph[c][x][y], (int64_t)d);
companyGraph[c][y][x] = std::min(companyGraph[c][y][x], (int64_t)d);
}
for (auto& e: companyGraph)
for (int i{}; i < n; i++)
e[i][i] = 0;
vvi graph(n, vi(n, 1ll << 60));
vi p(company);
for (auto& e: p) scanf("%d", &e);
for (int c_i{}; c_i < company; c_i++)
{
// {point, cost, cost_delta}
vi3 costs(p[c_i]);
for (int i{1}; i < p[c_i]; i++)
scanf("%d", &costs[i][0]);
for (int i{}; i < p[c_i]; i++)
scanf("%d", &costs[i][2]);
for (int i{1}; i < p[c_i]; i++)
costs[i][1] = costs[i - 1][1] + costs[i - 1][2] * (costs[i][0] - costs[i - 1][0]);
auto& eachGraph{companyGraph[c_i]};
for (int mid{}; mid < n; mid++)
for (int from{}; from < n; from++)
for (int to{}; to < n; to++)
eachGraph[from][to] = std::min(eachGraph[from][to], eachGraph[from][mid] + eachGraph[mid][to]);
for (int i{}; i < n; i++)
for (int j{}; j < n; j++)
{
int64_t dist{eachGraph[i][j]};
if (dist == (1ll << 60)) continue;
int64_t left{}, right{p[c_i]};
while (right - left > 1)
{
int64_t mid{(right + left) >> 1};
if (costs[mid][0] <= dist) left = mid;
else right = mid;
}
graph[i][j] = std::min(graph[i][j], costs[left][1] + costs[left][2] * (dist - costs[left][0]));
}
}
vi dist(n, 1ll << 60);
dist[start] = 0;
using pii = std::pair<int64_t, int>;
std::priority_queue<pii, std::vector<pii>, std::greater<pii>> dij;
dij.push({0, start});
while (!dij.empty())
{
auto now{dij.top()};
dij.pop();
if (now.first > dist[now.second]) continue;
for (int i{}; i < n; i++)
if (now.first + graph[now.second][i] < dist[i])
{
dist[i] = now.first + graph[now.second][i];
dij.push({dist[i], i});
}
}
if (dist[goal] == (1ll << 60)) puts("-1");
else printf("%lld\n", dist[goal]);
}
};
int main()
{
while (!Solve().is_last_query);
return 0;
}
``` |
#include <iostream>
#include <vector>
using namespace std;
int main(){
const long long INF = 1e9;
int N, M, C, S, G;
while(cin >> N >> M >> C >> S >> G, N){
--S,--G;
vector<vector<vector<long long>>> D(C,vector<vector<long long>>(N,vector<long long>(N,INF)));
for(int i = 0; i < M; ++i){
int x, y, d, c;
cin >> x >> y >> d >> c;
--x,--y,--c;
D[c][x][y] = min<long long>(D[c][x][y],d);
D[c][y][x] = min<long long>(D[c][y][x],d);
}
for(auto &d : D){
for(int i = 0; i < N; ++i) d[i][i] = 0;
for(int k = 0; k < N; ++k)
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
d[i][j] = min(d[i][j],d[i][k]+d[k][j]);
}
vector<long long> P(C);
for(int i = 0; i < C; ++i) cin >> P[i];
vector<vector<long long>> E(N,vector<long long>(N,INF));
for(int i = 0; i < C; ++i){
vector<long long> Q(P[i]+1), R(P[i]+1);
for(int j = 0; j+1 < P[i]; ++j) cin >> Q[j+1];
Q.back() = INF;
for(int j = 0; j < P[i]; ++j) cin >> R[j+1];
vector<long long> T(P[i]+1);
for(int j = 1; j <= P[i]; ++j){
T[j] += T[j-1];
T[j] += (Q[j]-Q[j-1])*R[j];
}
for(int j = 0; j < N; ++j){
for(int k = 0; k < N; ++k){
if(j == k) continue;
int d = D[i][j][k];
if(d >= INF) continue;
int idx = lower_bound(Q.begin(), Q.end(), d) - Q.begin();
long long cost = (d-Q[idx-1])*R[idx] + T[idx-1];
E[j][k] = min(E[j][k],cost);
}
}
}
for(int i = 0; i < N; ++i) E[i][i] = 0;
for(int k = 0; k < N; ++k)
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
E[i][j] = min(E[i][j],E[i][k]+E[k][j]);
int ans = E[S][G];
if(ans >= INF) ans = -1;
cout << ans << endl;
}
}
| ### Prompt
Please provide a CPP coded solution to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main(){
const long long INF = 1e9;
int N, M, C, S, G;
while(cin >> N >> M >> C >> S >> G, N){
--S,--G;
vector<vector<vector<long long>>> D(C,vector<vector<long long>>(N,vector<long long>(N,INF)));
for(int i = 0; i < M; ++i){
int x, y, d, c;
cin >> x >> y >> d >> c;
--x,--y,--c;
D[c][x][y] = min<long long>(D[c][x][y],d);
D[c][y][x] = min<long long>(D[c][y][x],d);
}
for(auto &d : D){
for(int i = 0; i < N; ++i) d[i][i] = 0;
for(int k = 0; k < N; ++k)
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
d[i][j] = min(d[i][j],d[i][k]+d[k][j]);
}
vector<long long> P(C);
for(int i = 0; i < C; ++i) cin >> P[i];
vector<vector<long long>> E(N,vector<long long>(N,INF));
for(int i = 0; i < C; ++i){
vector<long long> Q(P[i]+1), R(P[i]+1);
for(int j = 0; j+1 < P[i]; ++j) cin >> Q[j+1];
Q.back() = INF;
for(int j = 0; j < P[i]; ++j) cin >> R[j+1];
vector<long long> T(P[i]+1);
for(int j = 1; j <= P[i]; ++j){
T[j] += T[j-1];
T[j] += (Q[j]-Q[j-1])*R[j];
}
for(int j = 0; j < N; ++j){
for(int k = 0; k < N; ++k){
if(j == k) continue;
int d = D[i][j][k];
if(d >= INF) continue;
int idx = lower_bound(Q.begin(), Q.end(), d) - Q.begin();
long long cost = (d-Q[idx-1])*R[idx] + T[idx-1];
E[j][k] = min(E[j][k],cost);
}
}
}
for(int i = 0; i < N; ++i) E[i][i] = 0;
for(int k = 0; k < N; ++k)
for(int i = 0; i < N; ++i)
for(int j = 0; j < N; ++j)
E[i][j] = min(E[i][j],E[i][k]+E[k][j]);
int ans = E[S][G];
if(ans >= INF) ans = -1;
cout << ans << endl;
}
}
``` |
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int INF = 1000000000;
#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)
#define rep(i,n) REP(i, 0, n)
int fare[101][101], dist[21][101][101];
int cost[101];
int P[21];
int N, M, C, S, G;
typedef pair<int, int> pint;
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
while(cin >> N >> M >> C >> S >> G && N){
S--; G--;
rep(i, 21) rep(j, 101) rep(k, 101) dist[i][j][k] = INF;
rep(i, 21) rep(j, 101) dist[i][j][j] = 0;
rep(i, 101) rep(j, 101) fare[i][j] = INF;
rep(i, 101) fare[i][i] = 0;
int x_, y_, d_, c_;
rep(i, M){
cin >> x_ >> y_ >> d_ >> c_;
x_--; y_--; c_--;
dist[c_][x_][y_] = dist[c_][y_][x_] = min(dist[c_][x_][y_], d_);
}
rep(c, C) rep(k, N) rep(i, N) REP(j, i + 1, N)
dist[c][j][i] = dist[c][i][j] = min(dist[c][i][j], dist[c][i][k] + dist[c][k][j]);
rep(c, C) cin >> P[c];
rep(c, C){
vector<int> Q(P[c] + 1, INF), R(P[c]), f(P[c]);
REP(i, 1, P[c]) cin >> Q[i];
Q[0] = 0;
rep(j, P[c]) cin >> R[j];
f[0] = 0;
REP(i, 1, P[c]) f[i] = R[i - 1] * (Q[i] - Q[i - 1]) + f[i - 1];
rep(i, N - 1) REP(j, i + 1, N){
if(dist[c][i][j] == INF) continue;
int it = lower_bound(Q.begin(), Q.end(), dist[c][i][j]) - Q.begin();
it--;
int temp = f[it] + R[it] * (dist[c][i][j] - Q[it]);
fare[i][j] = fare[j][i] = min(fare[i][j], temp);
}
}
priority_queue<pint, vector<pint>, greater<pint> > que;
fill(cost, cost + N, INF);
cost[S] = 0;
que.push(pint(0, S));
while(!que.empty()){
pint now = que.top(); que.pop();
int v = now.second;
if(cost[v] < now.first) continue;
rep(i, N){
if(fare[v][i] == INF || v == i) continue;
if(cost[i] > cost[v] + fare[v][i]){
cost[i] = cost[v] + fare[v][i];
que.push(pint(cost[i], i));
}
}
}
int ans = cost[G];
if(ans == INF) ans = -1;
cout << ans << endl;
}
return 0;
} | ### Prompt
Develop a solution in Cpp to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int INF = 1000000000;
#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)
#define rep(i,n) REP(i, 0, n)
int fare[101][101], dist[21][101][101];
int cost[101];
int P[21];
int N, M, C, S, G;
typedef pair<int, int> pint;
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
while(cin >> N >> M >> C >> S >> G && N){
S--; G--;
rep(i, 21) rep(j, 101) rep(k, 101) dist[i][j][k] = INF;
rep(i, 21) rep(j, 101) dist[i][j][j] = 0;
rep(i, 101) rep(j, 101) fare[i][j] = INF;
rep(i, 101) fare[i][i] = 0;
int x_, y_, d_, c_;
rep(i, M){
cin >> x_ >> y_ >> d_ >> c_;
x_--; y_--; c_--;
dist[c_][x_][y_] = dist[c_][y_][x_] = min(dist[c_][x_][y_], d_);
}
rep(c, C) rep(k, N) rep(i, N) REP(j, i + 1, N)
dist[c][j][i] = dist[c][i][j] = min(dist[c][i][j], dist[c][i][k] + dist[c][k][j]);
rep(c, C) cin >> P[c];
rep(c, C){
vector<int> Q(P[c] + 1, INF), R(P[c]), f(P[c]);
REP(i, 1, P[c]) cin >> Q[i];
Q[0] = 0;
rep(j, P[c]) cin >> R[j];
f[0] = 0;
REP(i, 1, P[c]) f[i] = R[i - 1] * (Q[i] - Q[i - 1]) + f[i - 1];
rep(i, N - 1) REP(j, i + 1, N){
if(dist[c][i][j] == INF) continue;
int it = lower_bound(Q.begin(), Q.end(), dist[c][i][j]) - Q.begin();
it--;
int temp = f[it] + R[it] * (dist[c][i][j] - Q[it]);
fare[i][j] = fare[j][i] = min(fare[i][j], temp);
}
}
priority_queue<pint, vector<pint>, greater<pint> > que;
fill(cost, cost + N, INF);
cost[S] = 0;
que.push(pint(0, S));
while(!que.empty()){
pint now = que.top(); que.pop();
int v = now.second;
if(cost[v] < now.first) continue;
rep(i, N){
if(fare[v][i] == INF || v == i) continue;
if(cost[i] > cost[v] + fare[v][i]){
cost[i] = cost[v] + fare[v][i];
que.push(pint(cost[i], i));
}
}
}
int ans = cost[G];
if(ans == INF) ans = -1;
cout << ans << endl;
}
return 0;
}
``` |
#include "bits/stdc++.h"
using namespace std;
const int INF = 1 << 28;
int dist[20][100][100];
int d[100][100];
int p[20], q[20][50], r[20][50];
int main() {
int n, m, c, s, g;
while (cin >> n >> m >> c >> s >> g, n) {
s--; g--;
fill((int*)dist, (int*)(dist + 20), INF);
for (int i = 0; i < c; i++) for (int j = 0; j < n; j++) dist[i][j][j] = 0;
for (int i = 0; i < m; i++) {
int x, y, d, num;
cin >> x >> y >> d >> num;
x--; y--;
num--;
dist[num][x][y] = dist[num][y][x] = min(dist[num][x][y], d);
}
for (int i = 0; i < c; i++) {
scanf("%d", &p[i]);
}
for (int i = 0; i < c; i++) {
for (int j = 0; j + 1 < p[i]; j++) {
scanf("%d", &q[i][j]);
}
for (int j = 0; j< p[i]; j++) {
scanf("%d", &r[i][j]);
}
}
for (int com = 0; com < c; com++) {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[com][i][j] = min(dist[com][i][j], dist[com][i][k] + dist[com][k][j]);
}
}
}
}
fill((int*)d, (int*)(d + n), INF);
for (int i = 0; i < n; i++) d[i][i] = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int tmp = INF;
for (int com = 0; com < c; com++) {
int cost = 0;
if (dist[com][i][j] == INF) continue;
if (p[com] == 1) {
cost = dist[com][i][j] * r[com][0];
tmp = min(tmp, cost);
continue;
}
int prev = 0;
for (int k = 0; k + 1 < p[com]; k++) {
cost += (min(q[com][k], dist[com][i][j]) - prev)*r[com][k];
prev = q[com][k];
if (q[com][k] > dist[com][i][j]) break;
}
cost += max(dist[com][i][j] - q[com][p[com] - 2], 0)*r[com][p[com] - 1];
tmp = min(tmp, cost);
}
d[i][j] = tmp;
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
if (d[s][g] == INF) cout << -1 << endl;
else cout << d[s][g] << endl;
}
} | ### Prompt
Develop a solution in cpp to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include "bits/stdc++.h"
using namespace std;
const int INF = 1 << 28;
int dist[20][100][100];
int d[100][100];
int p[20], q[20][50], r[20][50];
int main() {
int n, m, c, s, g;
while (cin >> n >> m >> c >> s >> g, n) {
s--; g--;
fill((int*)dist, (int*)(dist + 20), INF);
for (int i = 0; i < c; i++) for (int j = 0; j < n; j++) dist[i][j][j] = 0;
for (int i = 0; i < m; i++) {
int x, y, d, num;
cin >> x >> y >> d >> num;
x--; y--;
num--;
dist[num][x][y] = dist[num][y][x] = min(dist[num][x][y], d);
}
for (int i = 0; i < c; i++) {
scanf("%d", &p[i]);
}
for (int i = 0; i < c; i++) {
for (int j = 0; j + 1 < p[i]; j++) {
scanf("%d", &q[i][j]);
}
for (int j = 0; j< p[i]; j++) {
scanf("%d", &r[i][j]);
}
}
for (int com = 0; com < c; com++) {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[com][i][j] = min(dist[com][i][j], dist[com][i][k] + dist[com][k][j]);
}
}
}
}
fill((int*)d, (int*)(d + n), INF);
for (int i = 0; i < n; i++) d[i][i] = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int tmp = INF;
for (int com = 0; com < c; com++) {
int cost = 0;
if (dist[com][i][j] == INF) continue;
if (p[com] == 1) {
cost = dist[com][i][j] * r[com][0];
tmp = min(tmp, cost);
continue;
}
int prev = 0;
for (int k = 0; k + 1 < p[com]; k++) {
cost += (min(q[com][k], dist[com][i][j]) - prev)*r[com][k];
prev = q[com][k];
if (q[com][k] > dist[com][i][j]) break;
}
cost += max(dist[com][i][j] - q[com][p[com] - 2], 0)*r[com][p[com] - 1];
tmp = min(tmp, cost);
}
d[i][j] = tmp;
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
if (d[s][g] == INF) cout << -1 << endl;
else cout << d[s][g] << endl;
}
}
``` |
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <cstring>
#include <climits>
#include <cmath>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
typedef pair<ll, int> ll_i;
typedef pair<double, int> d_i;
typedef pair<ll, ll> ll_ll;
struct edge { int u, v; ll w; };
void dijkstra(int n, vector<edge> G[], int s, ll d[]) {
fill(d, d + n, LLONG_MAX); d[s] = 0;
priority_queue<ll_i, vector<ll_i>, greater<ll_i> > q;
q.push(ll_i(0, s));
while (!q.empty()) {
ll_i p = q.top(); q.pop();
int u = p.second;
if (p.first > d[u]) continue;
for (int i = 0; i < G[u].size(); i++) {
edge e = G[u][i];
if (d[e.v] > d[u] + e.w) {
d[e.v] = d[u] + e.w;
q.push(ll_i(d[e.v], e.v));
}
}
}
}
vector<edge> G[100];
ll d[100];
int main() {
for (;;) {
int n, m, c, s, g;
cin >> n >> m >> c >> s >> g;
if (n == 0) break;
vector< vector< vector<int> > > a(c, vector< vector<int> >(n, vector<int>(n)));
for (int j = 0; j < c; j++)
for (int u = 0; u < n; u++)
for (int v = 0; v < n; v++)
a[j][u][v] = (u == v ? 0 : INT_MAX / 2);
for (; m > 0; m--) {
int x, y, d, c;
cin >> x >> y >> d >> c;
x--; y--; c--;
a[c][x][y] = min(a[c][x][y], d);
a[c][y][x] = min(a[c][y][x], d);
}
for (int j = 0; j < c; j++)
for (int k = 0; k < n; k++)
for (int u = 0; u < n; u++)
for (int v = 0; v < n; v++)
a[j][u][v] = min(a[j][u][v], a[j][u][k] + a[j][k][v]);
vector<int> p(c);
for (int j = 0; j < c; j++) cin >> p[j];
for (int u = 0; u < n; u++) G[u].clear();
for (int j = 0; j < c; j++) {
vector<int> q(p[j]), r(p[j]);
for (int k = 1; k < p[j]; k++) cin >> q[k];
for (int k = 0; k < p[j]; k++) cin >> r[k];
vector<int> f(p[j]);
for (int k = 1; k < p[j]; k++)
f[k] = f[k - 1] + r[k - 1] * (q[k] - q[k - 1]);
for (int u = 0; u < n; u++)
for (int v = 0; v < n; v++) {
int d = a[j][u][v];
if (d == INT_MAX / 2) continue;
int k = upper_bound(q.begin(), q.end(), d) - q.begin() - 1;
int w = f[k] + r[k] * (d - q[k]);
edge e = {u, v, w}; G[u].push_back(e);
}
}
dijkstra(n, G, s - 1, d);
cout << (d[g - 1] < LLONG_MAX ? d[g - 1] : -1) << endl;
}
} | ### Prompt
Please provide a cpp coded solution to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <cstring>
#include <climits>
#include <cmath>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
typedef pair<ll, int> ll_i;
typedef pair<double, int> d_i;
typedef pair<ll, ll> ll_ll;
struct edge { int u, v; ll w; };
void dijkstra(int n, vector<edge> G[], int s, ll d[]) {
fill(d, d + n, LLONG_MAX); d[s] = 0;
priority_queue<ll_i, vector<ll_i>, greater<ll_i> > q;
q.push(ll_i(0, s));
while (!q.empty()) {
ll_i p = q.top(); q.pop();
int u = p.second;
if (p.first > d[u]) continue;
for (int i = 0; i < G[u].size(); i++) {
edge e = G[u][i];
if (d[e.v] > d[u] + e.w) {
d[e.v] = d[u] + e.w;
q.push(ll_i(d[e.v], e.v));
}
}
}
}
vector<edge> G[100];
ll d[100];
int main() {
for (;;) {
int n, m, c, s, g;
cin >> n >> m >> c >> s >> g;
if (n == 0) break;
vector< vector< vector<int> > > a(c, vector< vector<int> >(n, vector<int>(n)));
for (int j = 0; j < c; j++)
for (int u = 0; u < n; u++)
for (int v = 0; v < n; v++)
a[j][u][v] = (u == v ? 0 : INT_MAX / 2);
for (; m > 0; m--) {
int x, y, d, c;
cin >> x >> y >> d >> c;
x--; y--; c--;
a[c][x][y] = min(a[c][x][y], d);
a[c][y][x] = min(a[c][y][x], d);
}
for (int j = 0; j < c; j++)
for (int k = 0; k < n; k++)
for (int u = 0; u < n; u++)
for (int v = 0; v < n; v++)
a[j][u][v] = min(a[j][u][v], a[j][u][k] + a[j][k][v]);
vector<int> p(c);
for (int j = 0; j < c; j++) cin >> p[j];
for (int u = 0; u < n; u++) G[u].clear();
for (int j = 0; j < c; j++) {
vector<int> q(p[j]), r(p[j]);
for (int k = 1; k < p[j]; k++) cin >> q[k];
for (int k = 0; k < p[j]; k++) cin >> r[k];
vector<int> f(p[j]);
for (int k = 1; k < p[j]; k++)
f[k] = f[k - 1] + r[k - 1] * (q[k] - q[k - 1]);
for (int u = 0; u < n; u++)
for (int v = 0; v < n; v++) {
int d = a[j][u][v];
if (d == INT_MAX / 2) continue;
int k = upper_bound(q.begin(), q.end(), d) - q.begin() - 1;
int w = f[k] + r[k] * (d - q[k]);
edge e = {u, v, w}; G[u].push_back(e);
}
}
dijkstra(n, G, s - 1, d);
cout << (d[g - 1] < LLONG_MAX ? d[g - 1] : -1) << endl;
}
}
``` |
# include <iostream>
# include <algorithm>
# include <vector>
# include <string>
# include <set>
# include <map>
# include <cmath>
# include <iomanip>
# include <functional>
# include <utility>
# include <stack>
# include <queue>
# include <list>
# include <tuple>
# include <unordered_map>
# include <numeric>
# include <complex>
# include <bitset>
# include <random>
# include <chrono>
# include <cstdlib>
# include <tuple>
# include <array>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
constexpr int INF = 2147483647;
constexpr int HINF = INF / 2;
constexpr double DINF = 100000000000000000.0;
constexpr double HDINF = 50000000000000000.0;
constexpr long long LINF = 9223372036854775807;
constexpr long long HLINF = 4500000000000000000;
const double PI = acos(-1);
template <typename T_char>T_char TL(T_char cX) { return tolower(cX); };
template <typename T_char>T_char TU(T_char cX) { return toupper(cX); };
const int vy[] = { -1, -1, -1, 0, 1, 1, 1, 0 }, vx[] = { -1, 0, 1, 1, 1, 0, -1, -1 };
const int dx[4] = { 0,1,0,-1 }, dy[4] = { 1,0,-1,0 };
# define ALL(x) (x).begin(),(x).end()
# define UNIQUE(c) sort(ALL((c)));(c).erase(unique(ALL((c))),(c).end())
# define LOWER(s) transform(ALL((s)),(s).begin(),TL<char>)
# define UPPER(s) transform(ALL((s)),(s).begin(),TU<char>)
# define FOR(i,a,b) for(LL i=(a);i<(b);i++)
# define RFOR(i,a,b) for(LL i=(a);i>=(b);i--)
# define REP(i,n) FOR(i,0,n)
# define INIT std::ios::sync_with_stdio(false);std::cin.tie(0)
int N, M, C, S, G;
int dis[32][128][128], p[32], q[32][64], r[32][64];
int fare[32][20010], cost[128][128];
int main() {
while (cin >> N >> M >> C >> S >> G && (N||M||C||S||G)) {
S--; G--;
REP(c, C)REP(i, N)REP(j, N) dis[c][i][j] = HINF;
REP(i, M) {
int x, y, d, c;
cin >> x >> y >> d >> c;
x--, y--, c--;
dis[c][x][y] = dis[c][y][x] = min(dis[c][x][y], d);
}
REP(c, C) cin >> p[c];
REP(c, C) {
REP(i, p[c] - 1) cin >> q[c][i];
REP(i, p[c]) cin >> r[c][i];
}
REP(c, C)REP(k, N)REP(i, N)REP(j, N) {
dis[c][i][j] = min(dis[c][i][j], dis[c][i][k] + dis[c][k][j]);
}
REP(c, C) {
int num = 0; fare[c][0] = 0;
REP(i, 20000) {
if (num < p[c] - 1 && i == q[c][num]) num++;
fare[c][i + 1] = fare[c][i] + r[c][num];
}
}
REP(i, N)REP(j, N) cost[i][j] = HINF;
REP(c, C)REP(i, N)REP(j, N) if (dis[c][i][j] < HINF) cost[i][j] = min(cost[i][j], fare[c][dis[c][i][j]]);
REP(k, N)REP(i, N)REP(j, N) cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j]);
cout << (cost[S][G] == HINF ? -1 : cost[S][G]) << endl;
}
}
| ### Prompt
Develop a solution in cpp to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
# include <iostream>
# include <algorithm>
# include <vector>
# include <string>
# include <set>
# include <map>
# include <cmath>
# include <iomanip>
# include <functional>
# include <utility>
# include <stack>
# include <queue>
# include <list>
# include <tuple>
# include <unordered_map>
# include <numeric>
# include <complex>
# include <bitset>
# include <random>
# include <chrono>
# include <cstdlib>
# include <tuple>
# include <array>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
constexpr int INF = 2147483647;
constexpr int HINF = INF / 2;
constexpr double DINF = 100000000000000000.0;
constexpr double HDINF = 50000000000000000.0;
constexpr long long LINF = 9223372036854775807;
constexpr long long HLINF = 4500000000000000000;
const double PI = acos(-1);
template <typename T_char>T_char TL(T_char cX) { return tolower(cX); };
template <typename T_char>T_char TU(T_char cX) { return toupper(cX); };
const int vy[] = { -1, -1, -1, 0, 1, 1, 1, 0 }, vx[] = { -1, 0, 1, 1, 1, 0, -1, -1 };
const int dx[4] = { 0,1,0,-1 }, dy[4] = { 1,0,-1,0 };
# define ALL(x) (x).begin(),(x).end()
# define UNIQUE(c) sort(ALL((c)));(c).erase(unique(ALL((c))),(c).end())
# define LOWER(s) transform(ALL((s)),(s).begin(),TL<char>)
# define UPPER(s) transform(ALL((s)),(s).begin(),TU<char>)
# define FOR(i,a,b) for(LL i=(a);i<(b);i++)
# define RFOR(i,a,b) for(LL i=(a);i>=(b);i--)
# define REP(i,n) FOR(i,0,n)
# define INIT std::ios::sync_with_stdio(false);std::cin.tie(0)
int N, M, C, S, G;
int dis[32][128][128], p[32], q[32][64], r[32][64];
int fare[32][20010], cost[128][128];
int main() {
while (cin >> N >> M >> C >> S >> G && (N||M||C||S||G)) {
S--; G--;
REP(c, C)REP(i, N)REP(j, N) dis[c][i][j] = HINF;
REP(i, M) {
int x, y, d, c;
cin >> x >> y >> d >> c;
x--, y--, c--;
dis[c][x][y] = dis[c][y][x] = min(dis[c][x][y], d);
}
REP(c, C) cin >> p[c];
REP(c, C) {
REP(i, p[c] - 1) cin >> q[c][i];
REP(i, p[c]) cin >> r[c][i];
}
REP(c, C)REP(k, N)REP(i, N)REP(j, N) {
dis[c][i][j] = min(dis[c][i][j], dis[c][i][k] + dis[c][k][j]);
}
REP(c, C) {
int num = 0; fare[c][0] = 0;
REP(i, 20000) {
if (num < p[c] - 1 && i == q[c][num]) num++;
fare[c][i + 1] = fare[c][i] + r[c][num];
}
}
REP(i, N)REP(j, N) cost[i][j] = HINF;
REP(c, C)REP(i, N)REP(j, N) if (dis[c][i][j] < HINF) cost[i][j] = min(cost[i][j], fare[c][dis[c][i][j]]);
REP(k, N)REP(i, N)REP(j, N) cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j]);
cout << (cost[S][G] == HINF ? -1 : cost[S][G]) << endl;
}
}
``` |
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define all(c) (c).begin(), (c).end()
const int inf = 1 << 28;
template<typename T> void chmin(T &t, T f){if(t > f)t = f;}
int n, m, c, s, g;
vector<vector<vector<int> > > dist, cost;
void init(){
dist.assign(c, vector<vector<int> >(n, vector<int>(n, inf)));
cost.assign(c, vector<vector<int> >(n, vector<int>(n, inf)));
rep(i, c)rep(j, n)dist[i][j][j] = cost[i][j][j] = 0;
}
void doWF(){
rep(r, c)rep(k, n)rep(i, n)rep(j, n){
chmin(dist[r][i][j], dist[r][i][k] + dist[r][k][j]);
}
}
void calc(int k, vector<int> q, vector<int> r){
vector<int> f(r.size());
rep(i, (int)q.size())f[i+1] = f[i] + (q[i] - (i? q[i-1]: 0)) * r[i];
q.insert(q.begin(), 0);
rep(i, n)rep(j, i){
if(dist[k][i][j] == inf)continue;
int p = upper_bound(all(q), dist[k][i][j]) - q.begin();
cost[k][i][j] = cost[k][j][i] = f[p-1] + (dist[k][i][j] - q[p-1]) * r[p-1];
}
}
int solve(){
vector<int> mem(n, inf);
mem[s] = 0;
priority_queue<pair<int, int> > q;
for(q.emplace(0, s); !q.empty();){
int cc = q.top().first, v = q.top().second; q.pop();
if(v == g)return -cc;
rep(r, c)rep(u, n){
if(dist[r][v][u] == inf)continue;
int nc = cost[r][v][u] - cc;
if(mem[u] <= nc)continue;
q.emplace(-(mem[u] = nc), u);
}
}
return -1;
}
int main(){
while(cin >> n >> m >> c >> s >> g, n|m|c|s|g){
s--; g--;
init();
while(m--){
int x, y, d, k;
cin >> x >> y >> d >> k;
x--; y--; k--;
chmin(dist[k][x][y], d);
dist[k][y][x] = dist[k][x][y];
}
doWF();
vector<int> p(c);
rep(i, c)cin >> p[i];
rep(i, c){
vector<int> q(p[i]-1), r(p[i]);
for(auto& x: q)cin >> x;
for(auto& x: r)cin >> x;
calc(i, q, r);
}
cout << solve() << '\n';
}
return 0;
} | ### Prompt
Please provide a CPP coded solution to the problem described below:
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortest distance does not necessarily mean the minimum cost. Assume the lines A-B, B-C, and C-D are operated by one railway company, and the line B-D is operated by another company. In this case, the path A->B->C->D may cost less than A->B->D. One of the reasons is that the fare is not proportional to the distance. Usually, the longer the distance is, the fare per unit distance is lower. If one uses lines of more than one railway company, the fares charged by these companies are simply added together, and consequently the total cost may become higher although the distance is shorter than the path using lines of only one company.
In this problem, a railway network including multiple railway companies is given. The fare table (the rule to calculate the fare from the distance) of each company is also given. Your task is, given the starting point and the goal point, to write a program that computes the path with the least total fare.
Input
The input consists of multiple datasets, each in the following format.
> n m c s g
> x1 y1 d1 c1
> ...
> xm ym dm cm
> p1 ... pc
> q1,1 ... q1,p1-1
> r1,1 ... r1,p1
> ...
> qc,1 ... qc,pc-1
> rc,1 ... rc,pc
>
Every input item in a dataset is a non-negative integer. Input items in the same input line are separated by a space.
The first input line gives the size of the railway network and the intended trip. n is the number of stations (2 ≤ n ≤ 100). m is the number of lines connecting two stations (0 ≤ m ≤ 10000). c is the number of railway companies (1 ≤ c ≤ 20). s is the station index of the starting point (1 ≤ s ≤ n ). g is the station index of the goal point (1 ≤ g ≤ n, g ≠ s ).
The following m input lines give the details of (railway) lines. The i -th line connects two stations xi and yi (1 ≤ xi ≤ n, 1 ≤ yi ≤ n, xi ≠ yi ). Each line can be traveled in both directions. There may be two or more lines connecting the same pair of stations. di is the distance of the i -th line (1 ≤ di ≤ 200). ci is the company index of the railway company operating the line (1 ≤ ci ≤ c ).
The fare table (the relation between the distance and the fare) of each railway company can be expressed as a line chart. For the railway company j , the number of sections of the line chart is given by pj (1 ≤ pj ≤ 50). qj,k (1 ≤ k ≤ pj-1) gives the distance separating two sections of the chart (1 ≤ qj,k ≤ 10000). rj,k (1 ≤ k ≤ pj ) gives the fare increment per unit distance for the corresponding section of the chart (1 ≤ rj,k ≤ 100). More precisely, with the fare for the distance z denoted by fj (z ), the fare for distance z satisfying qj,k-1+1 ≤ z ≤ qj,k is computed by the recurrence relation fj (z) = fj (z-1)+rj,k. Assume that qj,0 and fj (0) are zero, and qj,pj is infinity.
For example, assume pj = 3, qj,1 = 3, qj,2 = 6, rj,1 = 10, rj,2 = 5, and rj,3 = 3. The fare table in this case is as follows.
distance| 1| 2| 3| 4| 5| 6| 7| 8| 9
---|---|---|---|---|---|---|---|---|---
fare| 10| 20| 30| 35| 40| 45| 48| 51| 54
qj,k increase monotonically with respect to k . rj,k decrease monotonically with respect to k .
The last dataset is followed by an input line containing five zeros (separated by a space).
Output
For each dataset in the input, the total fare for the best route (the route with the minimum total fare) should be output as a line. If the goal cannot be reached from the start, output "-1". An output line should not contain extra characters such as spaces.
Once a route from the start to the goal is determined, the total fare of the route is computed as follows. If two or more lines of the same railway company are used contiguously, the total distance of these lines is used to compute the fare of this section. The total fare of the route is the sum of fares of such "sections consisting of contiguous lines of the same company". Even if one uses two lines of the same company, if a line of another company is used between these two lines, the fares of sections including these two lines are computed independently. No company offers transit discount.
Sample Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output for the Sample Input
54
-1
63
130
Example
Input
4 4 2 1 4
1 2 2 1
2 3 2 1
3 4 5 1
2 4 4 2
3 1
3 6
10 5 3
10
2 0 1 1 2
1
1
4 5 2 4 1
4 3 10 1
3 2 2 1
3 2 1 2
3 2 5 2
2 1 10 1
3 3
20 30
3 2 1
5 10
3 2 1
5 5 2 1 5
1 2 10 2
1 3 20 2
2 4 20 1
3 4 10 1
4 5 20 1
2 2
20
4 1
20
3 1
0 0 0 0 0
Output
54
-1
63
130
### Response
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define all(c) (c).begin(), (c).end()
const int inf = 1 << 28;
template<typename T> void chmin(T &t, T f){if(t > f)t = f;}
int n, m, c, s, g;
vector<vector<vector<int> > > dist, cost;
void init(){
dist.assign(c, vector<vector<int> >(n, vector<int>(n, inf)));
cost.assign(c, vector<vector<int> >(n, vector<int>(n, inf)));
rep(i, c)rep(j, n)dist[i][j][j] = cost[i][j][j] = 0;
}
void doWF(){
rep(r, c)rep(k, n)rep(i, n)rep(j, n){
chmin(dist[r][i][j], dist[r][i][k] + dist[r][k][j]);
}
}
void calc(int k, vector<int> q, vector<int> r){
vector<int> f(r.size());
rep(i, (int)q.size())f[i+1] = f[i] + (q[i] - (i? q[i-1]: 0)) * r[i];
q.insert(q.begin(), 0);
rep(i, n)rep(j, i){
if(dist[k][i][j] == inf)continue;
int p = upper_bound(all(q), dist[k][i][j]) - q.begin();
cost[k][i][j] = cost[k][j][i] = f[p-1] + (dist[k][i][j] - q[p-1]) * r[p-1];
}
}
int solve(){
vector<int> mem(n, inf);
mem[s] = 0;
priority_queue<pair<int, int> > q;
for(q.emplace(0, s); !q.empty();){
int cc = q.top().first, v = q.top().second; q.pop();
if(v == g)return -cc;
rep(r, c)rep(u, n){
if(dist[r][v][u] == inf)continue;
int nc = cost[r][v][u] - cc;
if(mem[u] <= nc)continue;
q.emplace(-(mem[u] = nc), u);
}
}
return -1;
}
int main(){
while(cin >> n >> m >> c >> s >> g, n|m|c|s|g){
s--; g--;
init();
while(m--){
int x, y, d, k;
cin >> x >> y >> d >> k;
x--; y--; k--;
chmin(dist[k][x][y], d);
dist[k][y][x] = dist[k][x][y];
}
doWF();
vector<int> p(c);
rep(i, c)cin >> p[i];
rep(i, c){
vector<int> q(p[i]-1), r(p[i]);
for(auto& x: q)cin >> x;
for(auto& x: r)cin >> x;
calc(i, q, r);
}
cout << solve() << '\n';
}
return 0;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.